Python3 常用字符串操作

生成字符串

.join()方法生成字符串 

 1 list1 = ['abc', 'DEF', 123]
 2 list2 = [str(i) for i in list1]
 3 # 使用列表推导式,把列表中元素统一转化为str类型
 4 list3 = ' ' .join(list2)
 5 # 把列表中的元素用空格隔开,用.join()方法将序列中的元素以指定的字符连接生成一个新的字符串。
 6 print(type(list1), list1)
 7 print(type(list2), list2)
 8 print(type(list3), list3)
 9 # 输出结果
10 # <class 'list'> ['abc', 'DEF', 123]
11 # <class 'list'> ['abc', 'DEF', '123']
12 # <class 'str'> abc DEF 123

 很多地方很多时候生成了元组、列表、字典后,可以用 join() 来转化为字符串。

清理字符串

1. strip()方法:

1 str1 = ' a b c d e '
2 print(str1.strip())
3 
4 # 'a b c d e'

>> 移除字符串首尾指定的字符(默认为空格或换行符)或字符序列。

>> .lstrip() 和 .rstrip() 方法分别指定截取左边或右边的字符

1 str2 = "     this is string example....wow!!!     "
2 print(str2.lstrip())
3 str3 = "88888888this is string example....wow!!!8888888"
4 print(str3.rstrip('8'))
5 
6 # this is string example....wow!!!     
7 # 88888888this is string example....wow!!!

 

2. replace()方法:

该方法主要用于字符串的替换replace(old, new, max)

>>返回字符串中的 old(旧字符串) 替换成 new (新字符串)后生成的新字符串,如果指定第三个参数 max,则替换不超过 max 次。

1 str1 = " a b c d e "
2 print(str1 .replace(" ", ""))
3 
4 # 'abcde'

 

3. join()+split()方法:

1 str1 = ' a b c d e '
2 "".join(str1.split(' '))
3 
4 # abcde

 

字符串内容统计

.count()方法

参数(str, beg= 0,end=len(string))

返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数

str="www.runoob.com"
sub='o'
print ("str.count('o') : ", str.count(sub))

sub='run'
print ("str.count('run', 0, 10) : ", str.count(sub,0,10))

# str.count('o') : 3
# str.count('run', 0 10) : 1

 

字符串切分

.split()方法

参数(str="", num=string.count(str))

num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串。返回分割后的字符串列表。

str = "this is string example....wow!!!"
print (str.split( ))       # 以空格为分隔符
print (str.split('i',1))   # 以 i 为分隔符
print (str.split('w'))     # 以 w 为分隔符

# ['this', 'is', 'string', 'example....wow!!!']
# ['th', 's is string example....wow!!!']
# ['this is string example....', 'o', '!!!']

 

posted @ 2019-12-07 10:22  Kogisune  阅读(648)  评论(0编辑  收藏  举报