.strip在python中不工作

2024-05-10 21:28:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我不太明白。脱衣舞的功能。

说我有根绳子

xxx = 'hello, world'

我想去掉逗号。 为什么不

print xxx.strip(',')

工作?


Tags: 功能helloworldxxxstripprint逗号绳子
3条回答

str.strip()仅从字符串的开始和结束中删除字符。从^{} documentation

Return a copy of the string with the leading and trailing characters removed.

强调我的。

使用^{}从字符串中的任何位置删除文本:

xxx.replace(',', '')

对于字符集使用正则表达式:

import re

re.sub(r'[,!?]', '', xxx)

演示:

>>> xxx = 'hello, world'
>>> xxx.replace(',', '')
'hello world'

^{}从字符串的开头或结尾移除字符,而不是在中间。

>>> ',hello, world,'.strip(',')
'hello, world'

如果要从任何位置删除字符,应使用^{}代替:

>>> 'hello, world'.replace(',', '')
'hello world'

您还可以使用string类的translate方法。如果为表参数传入None,则只执行字符删除步骤。

>>> 'hello, world'.translate(None,',')
'hello world'

相关问题 更多 >