关于Python去除字符串中空格的方法总结

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

关于Python去除字符串中空格的方法总结

黄佳俊、   2022-12-05 我要评论

需要将字符串中的空格去掉的情况,可以使用下面几种解决方法:

1、strip()方法:该方法只能把字符串头和尾的空格去掉,但是不能将字符串中间的空格去掉。

s=' This is a demo '

print(s.strip())

结果:"This is a demo"

lstrip():该方法只能把字符串最左边的空格去掉。

s=' ! This is a demo '
l='!'
print(s.lstrip()+l)

结果:"! This is a demo !"

rstrip():该方法只能把字符串最右边的空格去掉。

s=' ! This is a demo '
l='!'
print(s.rstrip()+l)

结果:"! This is a demo!"

2.replace(m,n)方法:将字符串里面的m替换为n。

#将字符串中所有的空格删除
s=' This is a demo '
print(s.replace(' ',''))

结果:"Thisisademo"

3.split(s,num)方法:split(s,num)

#使用join()方法将字符串中所有的空格删除
s=' This is a demo '
print(''.join(s.split()))

结果:"Thisisademo"

其中,join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

格式如下:

s.join(sequence)

元素之间的分隔符是s,sequence是要连接的元素序列。

补充:split()、join()方法同时使用

作用:删除字符串里面所有的空格

>>> str = '     h    e    l    l     '
>>> str1 = str.split()
>>> str2 = ''.join(str1)
>>> print(str2)
hell
>>>

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们