如何从另一个字符串中删除一个强字符

时间:2018-06-18 18:04:25

标签: python python-2.7

对于作业,我试图从用户输入的句子中剥离用户输入的一组字符。这是我到目前为止使用Python 2.7编写的代码:

    sentence = raw_input("Please write a sentence. ")
    remove = raw_input("Please input characters to remove from sentence. ")

    remove = remove.strip(" ") # in case user added spaces
    sentence = sentence.strip(remove)
    print sentence

4 个答案:

答案 0 :(得分:0)

我建议使用regex并利用character class,如下所示:

import re
sentence = raw_input("Please write a sentence. ")
remove = raw_input("Please input characters to remove from sentence. ")
regex = "[" + re.escape(remove) + "]"
sentence = re.sub(regex, "", sentence)
print(sentence)

它接受用户输入并转义任何特殊的正则表达式字符。这样,如果用户输入.*,则不会产生意外结果。然后用""替换任何这些字符,这些都不算什么。

答案 1 :(得分:0)

使用sentence.replace(remove, "")将特定字符替换为空字符串,换句话说,删除特定字符串。

在您的代码中,sentence.strip(remove)无法正常工作,因为它只会从字符串的 end 中删除单词。

答案 2 :(得分:0)

正如HUAN在答案中所说,sentence.strip只会从句子字符串的开头和结尾删除字符,要删除之间的字母,你应该使用sentence.replace,这里是你的代码我重写为使用replace,我还使用for循环来删除多个字符,所以如果用户输入类似" hw"句子"你好世界"成为" ello orld":

sentence = raw_input("Please write a sentence. ")
remove = raw_input("Please input characters to remove from sentence. ")

remove = remove.strip(" ") # in case user added spaces
for c in remove:
    sentence = sentence.replace(c,"")
print sentence

答案 3 :(得分:0)

这对我来说必须使用循环:

   sentence = raw_input("Please write a sentence. ")
   remove = raw_input("Please input characters to remove from sentence. ")

   remove = remove.replace(" ", "")
   i = 0
   while i < len(remove):
       sentence = sentence.replace(remove[i], "")
       i += 1
   print sentence