我想从字符串,两端和单词之间消除所有空格.
我有这个Python代码:
def my_handle(self):
sentence = ' hello apple '
sentence.strip()
Run Code Online (Sandbox Code Playgroud)
但这只会消除字符串两边的空白.如何删除所有空格?
我尝试做一个简单的字符串替换,但我不知道为什么它似乎不起作用:
X = "hello world"
X.replace("hello", "goodbye")
Run Code Online (Sandbox Code Playgroud)
我想将单词更改hello为goodbye,因此它应该将字符串更改"hello world"为"goodbye world".但X仍然存在"hello world".为什么我的代码不起作用?
我正在尝试替换字符串中的某些内容.这是我正在测试的代码:
stringT = "hello world"
print(stringT)
stringT.replace("world", "all")
print(stringT)
Run Code Online (Sandbox Code Playgroud)
我希望第二个输出能说"你好所有",但两次都说"你好世界".没有错误,代码运行正常,它只是没有做任何事情.我该如何解决?
我想了解两条代码行之间的区别。我找不到区别。每当我尝试运行第二个代码时,它都不会影响字符串a。
有人能告诉我为什么第二行代码不起作用吗?
a = "aaaaIstanbulaaaa".strip('a') #Affects the string
print(a)
>>>Istanbul
Run Code Online (Sandbox Code Playgroud)
a = "aaaaIstanbulaaaa" #Doesn't affect the string
a.strip('a')
print(a)
>>>aaaaIstanbulaaaa
Run Code Online (Sandbox Code Playgroud) txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x) // True
txt = "The rain in Spain stays mainly in the plain "
x = " " in txt
print(x) // True
txt = "The rain in Spain stays mainly in the plain "
x = " " in txt.strip()
print(x) // True ,
Run Code Online (Sandbox Code Playgroud)
即使删除空格后它也是真实的。