添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
本文介绍了使用Python处理字符串中空格的多种方法,包括利用lstrip(), rstrip(), strip()去除两端空格,以及使用replace(), split(), join()和正则表达式等手段去除中间空格。 摘要生成于 ,由 DeepSeek-R1 满血版支持,

3、strip:删除两端的空格
有的时候我们读取文件中的内容,每行2边都有空格,能不能一次性全部去掉呢,字符符有一个内置的strip()方法可以做到。

>>> s = “   这是一个字符串    ”
>>> s.strip()
'string'

二、python去除字符串中间空格的方法

1、使用字符串函数replace

>>> a = 'hello world'
>>> a.replace(' ', '')
'helloworld'

2、使用字符串函数split

>>> a = ''.join(a.split())
>>> print(a)
helloworld

3、使用正则表达式

>>> import re
>>> strinfo = re.compile()
>>> strinfo = re.compile(' ')
>>> b = strinfo.sub('', a)
>>> print(b)
helloworld
s.strip(rm)        删除s字符串中开头、结尾处,位于 rm删除序列的字符
s.lstrip(rm)       删除s字符串中开头处,位于 rm删除序列的字符
s.rstrip(rm)      删除s字符串中结尾处,位于 rm删除序列的字符
2. 当rm为空时,默认删除空白符(包括'\n...
s = '  hello world  '
s = re.sub(r'\s+', '', s)  # 将所有空格替换为空字符
print(s)  # 输出:'helloworld'
				npm 报错:npm ERR! missing script: start npm ERR! A complete log of this run can be found in: npm ERR!
					80002
                【Bug解决】docker Desktop在macos上无法登录Post “https://login.docker.com/oauth/token“: context deadline exceed
                    Jinjy-03: 
                    感谢🌹终于解决了!!!
                wampserver变橙色,apache 服务无法启动!问题解决小记(安装失败亦可参考)
                    2501_91318338: 
                    非常感谢!80端口没有占用 重下了vc2010和2008的 还是不能  最后卸了重装 跳出apach 点了是 打开后就变绿了表情包表情包表情包
                【Bug 解决】Error:failed to solve failed to do request:Head “https://registry-1.docker.io/v2/library/xxx
                    Derekzl: 
                    请问,这个问题出现的原因是应该docker镜像源原因吗?
                【Bug 解决】Error:failed to solve failed to do request:Head “https://registry-1.docker.io/v2/library/xxx
                    HuangYYTT001: 
                    docker system prune -a --force
执行这个把我全部docker镜像都删除了,包括正在使用的。
                【Bug解决】docker Desktop在macos上无法登录Post “https://login.docker.com/oauth/token“: context deadline exceed
                    要么出众,要么出局: 
                    感谢博主指导,问题已解决
            【Bug 解决】Error:failed to solve failed to do request:Head “https://registry-1.docker.io/v2/library/xxx
            【Bug解决】docker Desktop在macos上无法登录Post “https://login.docker.com/oauth/token“: context deadline exceed