Skip to main content
 首页 » 编程设计

python之.strip 在 python 中不起作用

2025年05月04日10yyy_WW

我不太了解 .strip 函数。

假设我有一个字符串

xxx = 'hello, world' 

我想去除逗号。 为什么不

print xxx.strip(',') 

工作?

请您参考如下方法:

str.strip() 仅从字符串的开头和结尾 删除字符。来自str.strip() documentation :

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

强调我的。

使用str.replace()从字符串中的任何地方删除文本:

xxx.replace(',', '') 

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

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

演示:

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