随笔_Python3 去除字符串中的空格

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

猜你喜欢

转载自www.cnblogs.com/Raine/p/12000819.html
今日推荐