.strip在Python中无效

1 投票
3 回答
8208 浏览
提问于 2025-04-18 01:52

我不太明白.strip这个函数。

假设我有一个字符串

xxx = 'hello, world'

我想去掉里面的逗号。为什么

print xxx.strip(',')

这样做不行呢?

3 个回答

1

你还可以使用string类的translate方法。如果你把None传给表参数,那么就只会执行删除字符的步骤。

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

str.strip 是用来去掉字符串开头和结尾的字符,但它不会去掉中间的字符。

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

如果你想要把字符从字符串的任何位置都去掉,那就应该使用 str.replace

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

str.strip() 这个方法只会去掉字符串开头和结尾的字符。根据str.strip() 的说明

返回一个去掉了开头和结尾字符的字符串副本。

这是我特别强调的。

如果你想要从字符串的任何位置去掉文字,可以使用str.replace()这个方法:

xxx.replace(',', '')

如果你想去掉一组字符,可以使用正则表达式:

import re

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

示例:

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

撰写回答