首页 > 解决方案 > Python:如何用@符号替换字符串中的元音

问题描述

我有一个关于用符号“@”替换元音(aeiou 上/下)的问题。我写了一个完整的代码,它也只打印大写字母(工作)、字符串中的每个其他字符(工作)和字符串中的位数(工作)。我在程序中遇到的唯一问题是我无法用符号“@”替换字符串中的所有元音,也无法输出字符串中每个元音的位置。我在 Python 的低级编码课程中,所以我只使用循环来完成程序。这是我到目前为止所拥有的:

str=input("Enter a string: ")
char=0
s=0
onlyCaps=0
v=0
n=0
count=0
countv=0
vowels=('a' and 'A' or 'e' and 'E' or 'i' and 'I' or 'o' and 'O' or 'u' and 'U')
position=vowels
def upperOnly(s):
    onlyCaps=""
    for char in s:
        if char.isupper()==True:
            onlyCaps+=char
    return onlyCaps
for n in str:
    if n.isnumeric():
        count=count+1
if str.__contains__(vowels):
    countv+=1
print(upperOnly(str))
print(str[::2])
print(str.replace(vowels,'@'))
print("The string contains",count,"digits.")
print("The vowels are at positions:",countv)

输出:

Ti 坐 2。

这是一个测试 123。(字符串应该将元音替换为“@”)

该字符串包含 3 位数字。

元音的位置:0(给出元音的位置)

标签: python

解决方案


您可以为此使用正则表达式(第三行是重要的,其他只是支持):

import re
line = "My hovercraft is full of ANNOYING eels"
line = re.sub("[aeiou]", "@", line, flags = re.I)
print(line)

这输出:

My h@v@rcr@ft @s f@ll @f @NN@Y@NG @@ls

更详细地解释:

re.sub("[aeiou]", "@", line, flags = re.I)
        \_____/    V   \__/  \__________/
           |       |     |        |
           |       |     |        +-- ignore case (change upper and lower).
           |       |     +----------- string to use for input.
           |       +----------------- string to replace with.
           +------------------------- character class to replace (all vowels).

推荐阅读