gpt4 book ai didi

python - 写一个for循环去掉标点符号

转载 作者:太空宇宙 更新时间:2023-11-03 11:16:16 25 4
gpt4 key购买 nike

我的任务是编写一个 for 循环来删除字符串列表中的一些标点符号,并将答案存储在一个新列表中。我知道如何使用一个字符串执行此操作,但不知道如何在循环中执行此操作。

例如:phrases = ['hi there!', 'thanks!']

import string
new_phrases = []
for i in phrases:
if i not in string.punctuation

然后我在这一点上有点卡住了。我追加吗?我已经尝试过 yieldreturn,但我意识到这是针对函数的。

最佳答案

您可以更新当前列表或将新值附加到另一个列表中。更新会更好,因为它占用恒定空间,而追加占用 O(n) 空间。

phrases = ['hi there!', 'thanks!']
i = 0
for el in phrases:
new_el = el.replace("!", "")
phrases[i] = new_el
i += 1
print (phrases)

将给出输出:['hi there', 'thanks']

关于python - 写一个for循环去掉标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51058880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com