python字符串的常见方法
程序员文章站
2022-06-20 08:32:05
1、join方法:拼接字符串 >stra = "你是风儿我是沙"b = "@".join(a)print(b)>>>你@是@风@儿@我@是@沙2、strip方法:处理左右空格、\t、\n >str 还可以处理指定内容a.strip("x") a.lstrip a.rstrip()a = " Hell ......
1、join方法:拼接字符串------->str
a = "你是风儿我是沙"
b = "@".join(a)
print(b)
>>>你@是@风@儿@我@是@沙
2、strip方法:处理左右空格、\t、\n----->str
还可以处理指定内容a.strip("x") a.lstrip a.rstrip()
a = " hello world"
b = a.strip()
print(b)
>>>hello world
3、对应字符转化:str.maketrans/translate----->str
v = "abcdefghijklmnodsjjkkkee"#原字符串
m = str.maketrans("aeiou",'12345')#构造对应关系m
new_v = v.translate(m)#生成新关系
print(new_v)
>>>1bcd2fgh3jklmn4dsjjkkk22
4、partition字符串分割,分三段---->元祖
v = "abcdefghijklmnodsjjkkkee"
b = v.partition("s")
print(b)
>>>('abcdefghijklmnod', 's', 'jjkkkee')
5、split字符串分割,一刀两断,两刀三段,拿不到分割元素---->list
v = " abcbdefbghijk "
b = v.split()
c = v.split('b')
d = v.split('b',2)
print(1,b)
print(2,c)
print(3,d)
>>>1 ['abcbdefbghijk']
>>>2 [' a', 'c', 'def', 'ghijk ']
>>>3 [' a', 'c', 'defbghijk ']
6、splitlines按照\n进行分割----->list
a = "abcsjdfk\nfjsdjf\njdfkdj\nsdfsf"
b = a.splitlines()(参数可以是true/false是否保留\n)
print(b)
for i in b:#处理文本方式
print(i)
>>>['abcsjdfk', 'fjsdjf', 'jdfkdj', 'sdfsf']
7、find方法:返回int,第一个索引号
a = '123bcds'
b = a.find('b')
print(b,type(b))
>>>3 <class 'int'>
8、replace方法:
a = "11sb11we11gg11"
b = a.replace("11","@@",2)
print(b,type(b))
>>>@@sb@@we11gg11 <class 'str'>
下一篇: 微信产品推广择怎么做?产品的定位先明确