Python 字符串去除空格的方法
在处理Python代码字符串的时候,我们常会遇到要去除空格的情况,所以就总结了多种方法供大家参考。
1、strip()方法
去除字符串开头或者结尾的空格
str = " Hello world " str.strip() 输出: "Hello world"
2、lstrip()方法
去除字符串开头的空格
str = " Hello world " str.lstrip() 输出: 'Hello world '
3、rstrip()方法
去除字符串结尾的空格
str = " Hello world " str.lstrip() 输出: ' Hello world'
4、replace()方法
可以去除全部空格
# replace主要用于字符串的替换replace(old, new, count)
str = " Hello world " str.replace(" ","") 输出: "Helloworld"
5: join()方法+split()方法
可以去除全部空格
# join为字符字符串合成传入一个字符串列表,split用于字符串分割可以按规则进行分割
>>> a = " a b c " >>> b = a.split() # 字符串按空格分割成列表 >>> b ['a', 'b', 'c'] >>> c = "