我不太了解.strip功能。
说我有一个字符串
xxx = 'hello, world'
我想删掉逗号。 为什么没有
print xxx.strip(',')
工作?
答案 0 :(得分:10)
str.strip()
从字符串的开头和结尾删除字符。来自str.strip()
documentation:
返回删除前导和尾随字符的字符串副本。
强调我的。
使用str.replace()
从字符串中的任何位置删除文字:
xxx.replace(',', '')
对于 set 字符,请使用正则表达式:
import re
re.sub(r'[,!?]', '', xxx)
演示:
>>> xxx = 'hello, world'
>>> xxx.replace(',', '')
'hello world'
答案 1 :(得分:7)
str.strip
从字符串的开头或结尾删除字符,而不是在中间。
>>> ',hello, world,'.strip(',')
'hello, world'
如果您想从任何地方删除字符,请改为使用str.replace
:
>>> 'hello, world'.replace(',', '')
'hello world'
答案 2 :(得分:1)
您还可以使用 string 类的翻译方法。如果为表参数传入无,则只执行字符删除步骤。
>>> 'hello, world'.translate(None,',')
'hello world'