[英]See if there is a vowel before letter 'y' in a string
x = input()
vowels = ['a', 'e', 'i', 'o', 'u']
I am trying to use an if
statement that shows if y
is in the string (without knowing the position of the y
in the string).我正在尝试使用
if
语句来显示y
是否在字符串中(不知道y
在字符串中的位置)。
If there are any vowels before y
, print(1)
;如果
y
之前有元音,则print(1)
; if not print (2)
, and if there is no y
in the word print(3)
.如果没有
print (2)
,并且如果 word print(3)
没有y
。
import re
word = "wordy"
ypos = word.find("y")
if ypos != -1:
if(bool(re.search(('|'.join(["a","e","i","o","u"])),word[:ypos]))):
print("1")
else:
print("2")
else :
print("3")
>>> def y_in_word(word):
... if 'y' not in word:
... print 3
... elif any([x in word for x in ['ay', 'ey', 'iy', 'oy', 'uy']]):
... print 2
... else:
... print 1
...
>>>
>>> y_in_word('wordy')
1
>>> y_in_word('worday')
2
>>> y_in_word('worda')
3
>>>
Without using regex:不使用正则表达式:
x = input()
vowels = "aeiou"
for i in range(len(x)):
if x[i] == "y":
break
if x[i] != "y": # No y found
print(3)
else:
flag = 0
new_str = x[:i+1]
for ch in new_str:
if ch in vowels:
print(1)
flag += 1
break
if flag == 0:
print(2)
x = input()
vowels = ['a', 'e', 'i', 'o', 'u']
if 'y' in x:
# find the position of 'y' in the input string
y_position = x.index(y)
# loop through each vowel
for vowel in vowels:
# if the vowel is in the input string and its position is before y
if vowel in x and x.index(vowel) < y_position:
print(1)
break
# if we made it all the way through the loop without breaking, we did not find
# any vowels before y
else:
print(2)
else:
print(3)
First become lowercase and then judge先变成小写再判断
import re
x = input().lower()
m = re.findall("(?=a|e|i|o|u)\w*?(?=y)",x)
if "y" in x.lower():
if m:
print(1)
else:
print(2)
else:
print(3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.