相关疑难解决方法(0)

在Python中删除字符串中的所有空格

我想从字符串,两端和单词之间消除所有空格.

我有这个Python代码:

def my_handle(self):
    sentence = ' hello  apple  '
    sentence.strip()
Run Code Online (Sandbox Code Playgroud)

但这只会消除字符串两边的空白.如何删除所有空格?

python trim removing-whitespace

715
推荐指数
10
解决办法
154万
查看次数

除非分配输出,否则为什么不调用Python字符串方法呢?

我尝试做一个简单的字符串替换,但我不知道为什么它似乎不起作用:

X = "hello world"
X.replace("hello", "goodbye")
Run Code Online (Sandbox Code Playgroud)

我想将单词更改hellogoodbye,因此它应该将字符串更改"hello world""goodbye world".但X仍然存在"hello world".为什么我的代码不起作用?

python string replace

133
推荐指数
1
解决办法
10万
查看次数

Python字符串替换不起作用

我正在尝试替换字符串中的某些内容.这是我正在测试的代码:

stringT = "hello world"
print(stringT)
stringT.replace("world", "all")
print(stringT)
Run Code Online (Sandbox Code Playgroud)

我希望第二个输出能说"你好所有",但两次都说"你好世界".没有错误,代码运行正常,它只是没有做任何事情.我该如何解决?

python string

2
推荐指数
1
解决办法
6474
查看次数

使用strip()函数

我想了解两条代码行之间的区别。我找不到区别。每当我尝试运行第二个代码时,它都不会影响字符串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)

python strip

1
推荐指数
1
解决办法
44
查看次数

Python 字符串“in”运算符

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)

即使删除空格后它也是真实的。

python

-3
推荐指数
1
解决办法
131
查看次数

标签 统计

python ×5

string ×2

removing-whitespace ×1

replace ×1

strip ×1

trim ×1