我们从用户那里得到一个字符串,希望将其小写,删除元音,并在每个字母前添加“.”。例如,我们得到'aBAcAba'并将其更改为'.b.c.b'。两件早期的事情已经完成了,但我需要第三件的帮助
str = input()
str=str.lower()
for i in range(0,len(str)):
str=str.replace('a','')
str=str.replace('e','')
str=str.replace('o','')
str=str.replace('i','')
str=str.replace('u','')
print(str)
for j in range(0,len(str)):
str=str.replace(str[j],('.'+str[j]))
print(str)
您可以使用
str.join()
在所有现有字符之间放置一些字符,然后可以使用字符串连接将其再次放置在末尾:作为旁注,请不要使用
str
作为变量名。它是“string”数据类型的名称,如果您创建了一个名为它的变量,则无法再正确处理其他字符串string
、st
、s
等都可以,因为它们不是保留关键字str
在这里,我已经一步一步地进行了,首先将字符串转换为小写,然后检查单词是否不是元音,然后在最后一个字符串中添加一个点,然后将单词添加到最后一个字符串中
有几件事:
您应该避免使用变量名
str
,因为这是由内置项使用的,所以我将其更改为st
在第一部分中,不需要循环
replace
将替换子字符串的所有出现次数对于最后一部分,在字符串中循环并构建新字符串可能是最容易的。将这个答案限制在基本语法上,一个简单的
for
循环就可以了另一个潜在的改进:对于第二部分,您还可以编写一个循环(而不是五行单独的
replace
):使用更先进技术的其他可能性:
对于第二部分,可以使用正则表达式:
st = re.sub('[aeiou]', '', st)
对于第三部分,可以使用生成器表达式:
st_new = ''.join(f'.{c}' for c in st)
相关问题 更多 >
编程相关推荐