社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

如何在Python中从给定字符串中移除子字符串列表?

Hojung Kim • 6 年前 • 1901 次点击  

所以我得到了这个字符串,我正在遍历要删除的子字符串列表。在Ruby中,字符串是可变的,我只需要不断地更改原始字符串就可以了。但是,由于字符串在Python中是不可变的,所以我遇到了一些问题。

如果这是我的字符串,并且我正在尝试删除以下列表中的子字符串(次):

string = "Play soccer tomorrow from 2pm to 3pm @homies"
times = ['tomorrow', 'from 2pm to 3pm']

如何将此字符串作为所需的返回?

removed_times = "Play soccer @homies"

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52969
文章 [ 3 ]  |  最新文章 6 年前
Kiran Indukuri
Reply   •   1 楼
Kiran Indukuri    6 年前
string = "Play soccer tomorrow from 2pm to 3pm @homies"
times = ['tomorrow', 'from 2pm to 3pm']
removed_times = string
for x in times:
    removed_times = removed_times.replace(' ' + x + ' ', ' ')
print(removed_times)
#Play soccer @homies
Oliver.R
Reply   •   2 楼
Oliver.R    6 年前

你可以 split 子字符串上的字符串,然后 join 它又回到了一起:

string = "Play soccer tomorrow from 2pm to 3pm @homies"
times = ['tomorrow', 'from 2pm to 3pm']
for t in times:
    string = ''.join(string.split(t))

'Play soccer @homies' 因为在你的时代空间不会被捕捉和移除。

roadrunner
Reply   •   3 楼
roadrunner    6 年前

你可以用 str.replace() 将子字符串替换为 "" " " 替换后单词之间只有一个空格。你可以用 str.split() 和 str.join() 为了这个。

string = "Play soccer tomorrow from 2pm to 3pm @homies"

times = ["tomorrow", "from 2pm to 3pm"]

for time in times:
    string = string.replace(time, "")

print(" ".join(string.split()))
# Play soccer @homies

字符串在python中是不可变的,因此不能简单地使用 string.replace(time, "") . 你需要重新分配字符串 string = string.replace(time, "") .