Python-如何为用户输入的多个字符剥离字符串



作为作业,我必须设计一个接受字符串作为用户输入的程序。用户还必须输入一些想要从原始字符串中删除的字符(不止一个):

用户输入=快速的棕色狐狸跳过了懒惰的狗。要剥离的字符= a,e,i,o,u

result = the qck brown fx jmps of the lzy dg.

我将感激任何帮助。请保持代码简单。这个练习是关于字符串处理的。我已经讲过了环和线。没有列表,没有列表,没有推导式,没有字典,也没有函数。如果你能保持你的代码与我所涵盖的主题相关,我将不胜感激。

谢谢

string = input('Please type something: ')
characters = input('What characters would you like to strip: ')

for char in string:
for j in characters:
new_string = string.replace(char, '')
print(new_string)

您不需要遍历字符串,只需遍历要删除

的字符
string = 'The quick brown fox jumps over the lazy dog.'
characters = 'aeiou'
new_string = string
for char in characters:
new_string = new_string.replace(char, '')
print(new_string) # Th qck brwn fx jmps vr th lzy dg.

说明,您需要遍历字符串中的所有字符,并针对每个字符查看该字符是否在禁用字符中。

如果存在,则忽略对该字符的任何处理,否则,将该字符添加到列表

处理完整个字符串后,要再次使用str.join方法生成要返回字符串的字符列表

这是代码

string = 'The quick brown fox jumps over the lazy dog.'
characters = set('aeiou')
# store the character which are not to removed
string_characters =[]
for char in string:
# checking if letter in string is present in character or not in O(1) time
if char not in characters: 
string_characters.append(char)
new_string = ''.join(string_characters) # use join function to convert list of characters to a string 
print(new_string)

更简单的方法,不需要做函数。

_string = input("Please type something: ")
if _string == 'x':
exit()
else:
newstring = _string
print("nRemoving vowels from the given string")
vowels = ('a', 'e', 'i', 'o', 'u')
for x in _string.lower():
if x in vowels:
newstring = newstring.replace(x,"")
print(newstring)

结果:

那只褐色的老鼠跳起来了

或使用oneliners:

_string = input("Enter any string: ")
remove_str = ''.join([x for x in _string if x.lower() not in 'aeiou'])  
print(remove_str)

最新更新