为了账号安全,请及时绑定邮箱和手机立即绑定

Python 字符串“in”运算符

Python 字符串“in”运算符

白衣染霜花 2022-11-18 16:39:38
txt = "The rain in Spain stays mainly in the plain"x = "ain" in txtprint(x) // Truetxt = "The rain in Spain stays mainly in the plain "x = " " in txtprint(x) // Truetxt = "The rain in Spain stays mainly in the plain "x = " " in txt.strip()print(x) // True ,即使在删除空格之后,它也是真实的。
查看完整描述

4 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

strip()仅删除前导和尾随空格,而不是字符串中的所有空格。



查看完整回答
反对 回复 2022-11-18
?
繁花不似锦

TA贡献1851条经验 获得超4个赞

txt.replace(" ", "")这将删除所有空格。

如果您还想删除其他空格,

txt = "".join(txt.split())


查看完整回答
反对 回复 2022-11-18
?
一只甜甜圈

TA贡献1836条经验 获得超5个赞

txt = "The rain in Spain stays mainly in the plain "

txt.strip()

输出:


'The rain in Spain stays mainly in the plain'

stript()只是删除开头和结尾的空格,而不是字符串之间的空格。因此,以下陈述是正确的:


x = " " in txt.strip()

print(x)

输出:


True

有很多方法可以删除字符串中的所有空格:


1.split()


''.join(txt.split())

2.replace()


txt.replace(" ", "")

3、正则表达式:


import re

stringWithoutSpaces = re.sub(r"\s+", "", txt, flags=re.UNICODE)

所有这些的输出是:


'TheraininSpainstaysmainlyintheplain'


查看完整回答
反对 回复 2022-11-18
?
慕勒3428872

TA贡献1848条经验 获得超5个赞

strip() 删除前导字符和尾随字符。意味着文本看起来像这样

“西班牙的雨主要停留在平原”

但单词之间仍然有空格


查看完整回答
反对 回复 2022-11-18
  • 4 回答
  • 0 关注
  • 126 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信