python - 字符串上的条(字符)
问题描述
我试图从我的字符串中删除字符 '_'(下划线和空格)。第一个代码无法剥离任何东西。
word_1 的代码按我的意图工作。谁能启发我如何修改第一个代码以获得输出'ale'?
word = 'a_ _ le'
word.strip('_ ')
word_1 = '_ _ le'
word_1.strip('_ ')
'''
解决方案
你需要replace()
在这个用例中,而不是strip()
word.replace('_ ', '')
strip()
:
string.strip(s[, 字符])
返回删除了前导和尾随字符的字符串的副本。如果省略 chars 或 None,则删除空白字符。如果给定而不是 None,chars 必须是字符串;字符串中的字符将从调用此方法的字符串的两端剥离。
replace()
:
string.replace(s, old, new[, maxreplace])
返回字符串 s 的副本,其中所有出现的子字符串 old 都替换为 new。如果给出了可选参数 maxreplace,则替换第一个 maxreplace 出现。
推荐阅读
- javascript - 结果包含 ( ) 或 + 的 Vue/Lodash RegExp 问题
- telegram - Telethon AttributeError:“协程”对象没有属性“send_message”
- reactjs - 如何使用 React 测试库测试记忆化组件的回调?
- android - Jetpack Compose 设置问题:无法加载类 'org.jetbrains.kotlin.gradle.tasks.KotlinCompile'
- docker - 使用 Nginx lua 模块时出错:libluajit-5.1.so.2:无法打开共享对象文件:没有这样的文件或目录
- ssl - 从授权服务器中选择访问令牌的方法
- javascript - 可以一次向 Node/Express 服务器发送多个 post 请求吗?
- r - R 错误:'错误:`f` 必须是一个因子(或字符向量)。'
- javascript - Testcafe 授权后引入测试入口点
- google-cloud-platform - Cloud Composer Parallelism 问题 DAG 和 Tasks