如何删除列表中的重复元素?

时间:2014-10-14 08:23:55

标签: python string list

作业说:写一个读取句子的Python程序。程序将字符串(用户输入)转换为列表,并将该句子打印为字符串对象列表。然后程序使用循环从列表中删除任何标点符号(出现在标点符号列表中)。最后,程序将列表转换为字符串并打印句子而没有标点符号。以下标点符号列表需要复制到您的程序中:

标点符号= ['(',')','?',':',' ;',',','。','!',' /',' "',"'"," "]

注意:使用str类中的join方法将列表转换为字符串。

所以我基本上把它全部搞定了,这是我的代码:

#punctuation list
punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'", " "]

#make an empty list for string to list
converted_list = []
import copy
#tell user to input a sentence
sentence = str(input("Type in a line of text: "))

#Convert str to list
for char in sentence:
    converted_list.append(char)
    newlist = copy.deepcopy(converted_list)
    #remove punctuation from this list
    for character in newlist:
        if (character in punctuation):
            newlist.remove(character)
            newline = "".join(newlist)


print(converted_list)
print(newline)

但问题是,我的输出显示:

Type in a line of text: Hey! Where are you?
['H', 'e', 'y', '!', ' ', 'W', 'h', 'e', 'r', 'e', ' ', 'a', 'r', 'e', ' ', 'y', 'o', 'u', '?']
HeyWhereare you

它只删除第一个"空间"字符。我如何删除第二个"空间"在'之后?

3 个答案:

答案 0 :(得分:0)

尽量保持简单:

#punctuation list
punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'", " "]

#make an empty list for string to list
converted_list = []
#tell user to input a sentence
sentence = str(input("Type in a line of text: "))

#Convert str to list
for char in sentence:
    if char not in punctuation:
        converted_list.append(char)

print(converted_list)
print("".join(converted_list))

输出将是:

Type in a line of text: "Hey! Where are you?"
['H', 'e', 'y', 'W', 'h', 'e', 'r', 'e', 'a', 'r', 'e', 'y', 'o', 'u']
HeyWhereareyou

答案 1 :(得分:0)

试试这个

sentence = str(input("Type in a line of text: ")
punctuation = ['(', ')', '?', ':', ';', ',', '.', '!', '/', '"', "'", " "]
converted_list = [char for char in sentence if char not in punctuation]
print(converted_list)

答案 2 :(得分:-3)

为了删除字符串中的空格,我们可以使用nospace关键字。 例如:

str1 =“TH ABC 123”

str1sp = nospace(srt1)

打印(str1sp)

ANS:

THABC123

相关问题