字符串

字符串的定义

字符串是 Python 中最常用的数据类型。字符串的定义有4种:

>>> a = 'Hello world!'
>>> b = "Hello world!"
>>> c = '''Hello world!'''
>>> d = """Hello world!"""

python中字符串的常见方法

  • capitalize 首字母大写
>>> a
'hello world'
>>> a.capitalize()
'Hello world'
  • center 将字符串居中,第二个参数表示填充的符号
>>> a.center(15," ")
'  hello world  '
>>> a.center(50," ")
'                   hello world                    '
  • count 统计字符串中出现字符或者字符串次数
>>> a
'hello world'
>>> a.count("l")
3
>>> a.count("ll")
1
  • encode 按照编码格式编码字符串
>>> a = "haha"
>>> a.encode("utf-8")		将字符串转化为字节
b'haha'
  • endswith 判断字符是否以xx结尾
>>> a.endswith("d")
True
>>> a.endswith("h")
False
  • startswith 判断字符串是否以xxx开头
>>> a.startswith("h")
True
>>> a.startswith("d")
False
  • find 查找字符串中某个字符或者字符串第一次出现的位置,如果不存在,则返回-1
  • rfind 查找字符或者字符串最后一个出现的位置,如果不存在,则返回-1
>>> a.find("d")
10
>>> a.find("s")
-1
>>> a.rfind("s")
-1
>>> a.rfind("l")
9
  • index 查找字符串中某个字符或者字符串第一次出现的位置,如果不存在,则抛出异常
  • rindex 查找字符或者字符串最后一个出现的位置,如果不存在,则抛出异常
>>> a.index("d")
10
>>> a.index("s")
ValueError: substring not found
>>> a.rindex("s")
ValueError: substring not found
>>> a.rindex("l")
9
  • format 格式化字符串
>>> "{}{}".format("你","好")
'你好'
>>> "{0}{1}{2}{1}".format("你","好","不")
'你好不好'
  • join 用来拼接字符串,参数是一个可迭代对象
>>> a = "__"
>>> str =("haha","xixi","hehe")
>>> a.join(str)
'haha__xixi__hehe'
  • split 分割字符串,默认分割次数位-1,即分割所有,可修改
>>> a = "你 是 一 个 好 人"
>>> a.split(" ")
['你', '是', '一', '个', '好', '人']
>>> a.split(" ",1)		只分割一次
['你', '是 一 个 好 人']
  • lower 转小写
  • upper 转大写
>>> a ="dsanjloinDASUIHI"
>>> a.upper()
'DSANJLOINDASUIHI'
>>> a.lower()
'dsanjloindasuihi'
  • title 转换字符串为一个符合标题的规则
>>> a = "this is a big world"
>>> a.title()
'This Is A Big World'
  • strip 清除字符串两边的空格
  • rstrip 清除右边的空格
  • lstrip 清除左边的空格
>>> a = "        haha         "
>>> a.strip()
'haha'
>>> a.rstrip()
'        haha'
>>> a.lstrip()
'haha         '
  • replace 替换字符串
>>> a = "我是一个好人"
>>> a.replace("我","你")
'你是一个好人'

字符串的判断方法

str.istitle					判断字符串是不是标题
 str.isspace					判断是不是空白字符
 str.islower			 		判断是不是小写字母
 str.isupper			 		判断是不是大字母
 str.isalnum			 		判断是不是有字母和数字组成
 str.isalpha			 		判断是不是有字母组成
 str.isdigit			 		判断是不是数字组成

切片

切片是Python提供用来切割、分割、截取容器的方式,切片是一个前闭后开的区间。

>>> ls=[1,2,3,4,5,6,7,8,9]
  • 容器[start:] 从start位置开始截取容器,截取到末尾
>>> ls[3:]
[4, 5, 6, 7, 8, 9]
  • 容器[start:end] 从start位置开始,到end位置结束,不包含end位(左闭右开)
>>> ls[3:7]
[4, 5, 6, 7]
  • 容器[:end] 如果:左侧不写,默认(0)就下标为0的位置开始
>>> ls[:7]
[1, 2, 3, 4, 5, 6, 7]
  • 容器[start: end:step] step表示步长,默认是1,可以自己指定
>>> ls[2:7:2]
[3, 5, 7]
  • 容器[::-1] 翻转容器
>>> ls[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
  • 容器[start:] 若start大于len.容器,不会报错,返回空
>>> ls[20:]
[]