.strip无法在python中工作

Chr*_*ael 1 python string strip

我真的不懂.strip函数.

说我有一个字符串

xxx = 'hello, world'
Run Code Online (Sandbox Code Playgroud)

我想删除逗号.为什么不呢

print xxx.strip(',')
Run Code Online (Sandbox Code Playgroud)

工作?

Mar*_*ers 10

str.strip()仅从字符串开头和结尾删除字符.从str.strip()文档:

返回删除了前导和尾随字符的字符串副本.

强调我的.

用于str.replace()从字符串中的任何位置删除文本:

xxx.replace(',', '')
Run Code Online (Sandbox Code Playgroud)

对于一字符,请使用正则表达式:

import re

re.sub(r'[,!?]', '', xxx)
Run Code Online (Sandbox Code Playgroud)

演示:

>>> xxx = 'hello, world'
>>> xxx.replace(',', '')
'hello world'
Run Code Online (Sandbox Code Playgroud)


fal*_*tru 7

str.strip 从字符串的开头或结尾删除字符,而不是从中间删除.

>>> ',hello, world,'.strip(',')
'hello, world'
Run Code Online (Sandbox Code Playgroud)

如果你想从任何地方删除字符,你应该使用str.replace:

>>> 'hello, world'.replace(',', '')
'hello world'
Run Code Online (Sandbox Code Playgroud)