Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过将元音替换为字符串中的索引来删除元音_Python - Fatal编程技术网

Python 通过将元音替换为字符串中的索引来删除元音

Python 通过将元音替换为字符串中的索引来删除元音,python,Python,我试图用相同的索引替换给定字符串的元音。我试图使用.replace()和.index(),但它不起作用。 我有这样的想法: def vowels(w): vowel = 'aeiou' for i in w: if i in vowel: a = w.replace(i, w.index(str(w.find('aeiou')))) return a 这个想法是: 输入=‘大家好’ output='H1 3v5ry8n10'replace接受第三个参数,告诉它要

我试图用相同的索引替换给定字符串的元音。我试图使用.replace()和.index(),但它不起作用。 我有这样的想法:

def vowels(w):
vowel = 'aeiou'
for i in w:
    if i in vowel:
        a = w.replace(i, w.index(str(w.find('aeiou'))))
    return a
这个想法是:

输入=‘大家好’


output='H1 3v5ry8n10'

replace
接受第三个参数,告诉它要替换多少个字符。出于您的目的,您需要每次更换一个

index
将为您提供字符的位置,
str
将使其成为字符串

使用
lower
确保所有案例都匹配

替换
w
中使用的字符以包含重复字符。确保它是一个列表,并且替换字符不是单个字符,因此它适用于所有字符串

def vowels(w):
    vowel = 'aeiou'
    a = w
    w = list(w)
    for i in w:
        if i.lower() in vowel:
            a = a.replace(i, str(w.index(i)), 1)
            w[w.index(i)] = 0
    return a
在:
大家好


输出:
H13V5RY8N10
在这种情况下,使用
.replace()
不是一个好主意。通常,
.replace()
将对字符串中的所有元音执行一个操作,但在这种情况下,您希望用一个非常特定的值替换每个元音。使用
join
的生成器理解在这里更好:

vowels = set('aeiou')
s = "Hi Everyone"

replaced = ''.join(str(i) if c.lower() in vowels else c for i, c in enumerate(s))
print(replaced)
输出:

H1 3v5ry8n10

记住@Craig Meier的注释,在迭代时跟踪元素位置的最简单方法是使用
enumerate
。这使得
find
操作变得不必要,代码变得更简单

当然,@Primusa提出的方法是最具python风格的方法,但我认为展示一种更为循序渐进的方法是有价值的

def vowels(w):
    vowel = 'aeiou'
    for pos, char in enumerate(w):  # extract a character and remember its position
        if char.lower() in vowel:   # check if it belongs to the check set
            w = w.replace(char, str(pos), 1)  # replace just the first instance
    return w

inp = 'Hi Everyone'
output = vowels(inp)
print(output)

您可能希望使用与原始
w
分开的累加器,以便较长的字符串保留原始字符串的索引。否则,后面的元音将得到更大的索引,因为前面的元音将被两个或更多的数字替换(例如,
元音(“Hi EveryoneA”)
产生
“H1 3v5ry8n1012”
,而这可能会产生
“H1 3v5ry8n1011”
。@CraigMeier你说得对。我编辑了我的答案,这样代码就可以工作了。谢谢交换
i
c
有助于提高可读性。[i] ndex和[c]haracter@VikrantSharma,已编辑。我一直认为它们是重要的。