在python中如何在字符串中的每个字母前添加点

2024-10-04 09:25:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我们从用户那里得到一个字符串,希望将其小写,删除元音,并在每个字母前添加“.”。例如,我们得到'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)

Tags: 字符串用户inforinputlen字母range
3条回答

您可以使用str.join()在所有现有字符之间放置一些字符,然后可以使用字符串连接将其再次放置在末尾:

# st = 'bcb'
st = '.' + '.'.join(st)
# '.b.c.b'

作为旁注,请不要使用str作为变量名。它是“string”数据类型的名称,如果您创建了一个名为它的变量,则无法再正确处理其他字符串stringsts等都可以,因为它们不是保留关键字str

z = "aBAcAba"

z = z.lower() 
newstring = ''
for i in z:
  if not i in 'aeiou':
    newstring+='.'
    newstring+=i  


print(newstring)

在这里,我已经一步一步地进行了,首先将字符串转换为小写,然后检查单词是否不是元音,然后在最后一个字符串中添加一个点,然后将单词添加到最后一个字符串中

有几件事:

  • 您应该避免使用变量名str,因为这是由内置项使用的,所以我将其更改为st

  • 在第一部分中,不需要循环replace将替换子字符串的所有出现次数

  • 对于最后一部分,在字符串中循环并构建新字符串可能是最容易的。将这个答案限制在基本语法上,一个简单的for循环就可以了

st = input()
st=st.lower()
st=st.replace('a','')
st=st.replace('e','')
st=st.replace('o','')
st=st.replace('i','')
st=st.replace('u','')
print(st)
st_new = ''
for c in st:
    st_new += '.' + c
print(st_new)

另一个潜在的改进:对于第二部分,您还可以编写一个循环(而不是五行单独的replace):

for c in 'aeiou':
    st = st.replace(c, '')

使用更先进技术的其他可能性:

  • 对于第二部分,可以使用正则表达式:

    • st = re.sub('[aeiou]', '', st)
  • 对于第三部分,可以使用生成器表达式:

    • st_new = ''.join(f'.{c}' for c in st)

相关问题 更多 >