Python字符串

字符串(str)    不可变数据类型

常用操作:切片、长度、内容判断、替换、转换、分割等

创建

1 # 引号即可
2 name = "jack"

切片

1 name = "jackAndRose"
2 print(name[2])
3 # c
4 print(name[0: 2])
5 # ja
6 print(s[-1: 3: -2])
7 # eodA

长度

  用len()方法即可返回长度

内容判断

 1 s = "hello man! 234"
 2 # 判断符合条件返回True,否则为False
 3 # 是否全为数字
 4 s.isdigit()
 5 # 是否全为字母
 6 s.isalpha()
 7 # 是否为为数字或字母
 8 s.isalnum()
 9 # 非法字符判断, 同变量名规则
10 s.isidentifier()

内容转换

1 s = "jackAndRose"
2 # 大小写转换,转换返回相应的结果
3 s = s.upper()  # 全部转换为大写
4 s = s.lower()  # 全部转换为小写
5 s = s.swapcase()  # 大小互转
6 s = s.capitalize()  # 首字母大写

内容替换

1 s = "fat cat"
2 s = s.replace("a", "o")
3 print(s)
4 # fot cot

字符串拼接

1 s = "-".join(iterable)    # 此处将后面可迭代对象用 - 拼接为字符串
2 a = "hello"
3 b = " world"
4 s = a + b   # 效率低
5 # hello world

 

内置字符串方法

 1 s = "this is a string example"
 2 
 3 s.count("")    # 个数
 4 
 5 s = s.center(width, char)    # 总长width,s两边用char补不足位置
 6 s = "world"
 7 s = s.center(20, "-")
 8 # -------world--------
 9 # 类似于center的还有ljust和rjust
10 
11 # 判断开头,结尾,返回True或False
12 s.startwith("*")
13 s.endwith("*")
14 
15 s.find("*")   # 返回查找字符的第一个位置,无结果返回-1
16 s.index("*") #  查找相应字符的索引,类似find,但找不到会报错
17 
18 s.strip()    # 去除两端空格并返回,tab等,类似的还有lstrip和rstrip 
19            
20 s.replace(old, new, count)  # 替换字符
21 
22 s.split("*", max_sep)   # 以特定符号分割字符串,可以规定次数,默认最大次数分割,返回数组

 

posted @ 2019-08-25 17:45  彼时今日  阅读(227)  评论(0编辑  收藏  举报