如何删除字符串中的某些字符?

时间:2014-12-16 17:40:42

标签: string python-3.x replace

有没有办法这样做?这是我写的代码。另外,我正在使用最新的 Python版本:

import string

Finn = "It's Adventure Time!"
punctuation = string.punctuation
print(punctuation)
for punc in punctuation:
   if punc in Finn:
       Finn[18] = ' '
print(Finn)

我得到的错误是:

TypeError: 'str' object does not support item assignment

3 个答案:

答案 0 :(得分:1)

我希望你期待这个:

import string

Finn = "It's Adventure Time!"
punctuation = string.punctuation
print(punctuation)
for punc in punctuation:
   if punc in Finn:
       Finn = Finn.replace(punc, "")

print(Finn)

答案 1 :(得分:0)

一个非常简短的变体是:

import string

finn = "It's Adventure Time!"
print(finn)
table = str.maketrans("","",string.punctuation)
finn = finn.translate(table)
print(finn)

此解决方案需要python 3.(在OP中标记)

答案 2 :(得分:0)

最短的一个,我能想到:P

import string
finn = "It's Adventure Time!"
finn = ''.join(i for i in finn if i not in string.punctuation)