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)
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)
| 归档时间: |
|
| 查看次数: |
6391 次 |
| 最近记录: |