代码似乎没有替换字符串中的非元音字符。
def vowel_one(s):
not_vowel = '0'
vowels = {'a':'1',
'e':'1',
'i':'1',
'o':'1',
'u':'1'}
#dictionary with keys as vowels, and their values as 1
s = s.lower() #changing list to lowercase
vowelsList = list(s)
for index, item in enumerate(vowelsList): #counter, instead of doing i+=1, using enumerate
for key, value in vowels.items():
if item == key: #if character in string is equal to key in dictionary
vowelsList[index] = value #at the indexes of such characters, replace them with dictionary key values
if item != key and item != '1':
vowelsList[index] = not_vowel
return ("".join(vowelsList)) #removes brackets and ','
例如,"vowelOne“的结果应该是: 01010101,而不是: v1w1l1n1,为什么另一个如果语句不工作呢?我设想,如果给定列表(vowelsList)中的项不等于字典(元音)中的任何键,那么它应该替换为'0‘。如果我不嵌套If语句,那么我只会得到0。
指向kata:https://www.codewars.com/kata/580751a40b5a777a200000a1/的链接
发布于 2022-11-04 20:27:33
如果所有的值都是1
.
for loops
,这只会增加complexity.
string
转换为list
.的时间
这是我的密码:
def vowel_one(s):
vowels = ['a', 'e','i', 'o', 'u'] # simple list
#dictionary with keys as vowels, and their values as 1
s = s.lower() #changing list to lowercase
for i in s: # Iterating through every value
if i in vowels: # Check if sub-string in vowels
s = s.replace(i, '1')
else: # If not vowel replace with 0
s = s.replace(i, '0')
return s
print(vowel_one("vowelOne"))
编辑:,如果您想省略spaces
,可以添加一个elif
条件。尝试:
def vowel_one(s):
vowels = ['a', 'e','i', 'o', 'u'] # simple list
#dictionary with keys as vowels, and their values as 1
s = s.lower() #changing list to lowercase
for i in s: # Iterating through every value
if i in vowels: # Check if sub-string in vowels
s = s.replace(i, '1')
elif not i.isspace(): # If not vowel and space replace with 0
s = s.replace(i, '0')
return s
print(vowel_one("Mudith is my name"))
https://stackoverflow.com/questions/74322549
复制相似问题