Python3 去除空格

Posted TianchiLiu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python3 去除空格相关的知识,希望对你有一定的参考价值。

1 去除两端空格(strip())

a.去除左端空格 lstrip()

str0=\'abcdef\'
str1=\'  abcdef\'
print(str0)
print(str1.lstrip())

b.去除右端空格 rstrip()

str0=\'abcdef  \'
str1=\'abcdef  \'
print(str0)
print(str1.rstrip())

c.去除两端空格 strip()

str0=\'  abcdef  \'
str1=\'  abcdef  \'
print(str0)
print(str1.strip())

2 空格替换(replace() 推荐使用)

str0=\'  a b c d e f  \'
str1=\'  a b c d e f  \'
print(str0)
print(str1.replace(\' \',\'\'))

3 重新组合替换空格(使用split分割字符,使用join重新组合,效率低)

str0=\'  a b c d e f  \'
str1=\'  a b c d e f  \'
print(str0)
print(\'\'.join(str1.split()))

4 正则表达式去空格(用sub()方法替换)

import re
str0=\'  a b c d e f  \'
str1=\'  a b c d e f  \'
print(str0)print(re.sub(\' \',\'\',str1))

[1] https://www.cnblogs.com/146xwq/p/9684891.html

以上是关于Python3 去除空格的主要内容,如果未能解决你的问题,请参考以下文章