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 = \"\".join(b) # 使用一个空字符串合成列表内容生成新的字符串
>>> c \'abc\'
# 快捷用法
>>> \"\".join(a.split())
\'abc\'
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容