首页 > 解决方案 > 字符串上的条(字符)

问题描述

我试图从我的字符串中删除字符 '_'(下划线和空格)。第一个代码无法剥离任何东西。

word_1 的代码按我的意图工作。谁能启发我如何修改第一个代码以获得输出'ale'?

word = 'a_ _ le' 

word.strip('_ ')

word_1 = '_ _ le'
word_1.strip('_ ')
'''


标签: pythonstringstrip

解决方案


你需要replace()在这个用例中,而不是strip()

word.replace('_ ', '')

strip()

string.strip(s[, 字符])

返回删除了前导和尾随字符的字符串的副本。如果省略 chars 或 None,则删除空白字符。如果给定而不是 None,chars 必须是字符串;字符串中的字符将从调用此方法的字符串的两端剥离。

replace()

string.replace(s, old, new[, maxreplace])

返回字符串 s 的副本,其中所有出现的子字符串 old 都替换为 new。如果给出了可选参数 maxreplace,则替换第一个 maxreplace 出现。

Python中的字符串


推荐阅读