首页 > 解决方案 > Python text.replace 用于删除字符串的一部分

问题描述

我想看看如何在不留空白的情况下删除字符串的某个部分。

运行此代码时,它输出nice today,问题是我用空格替换字符。有没有解决这个问题或者我应该完全使用完全不同的方法?

text = ("hello bye there ")

print(text.replace("hello", "nice").replace("there","today").replace("bye", ""))

标签: pythonstringtextreplace

解决方案


你应该首先删除空格:

text = ("hello bye there ")
print(text.replace("hello", "nice").replace("there","today").replace(" ", '').replace("bye" , " "))

输出将是:

nice today

推荐阅读