我是Python新手,我试图打印字符串中的所有元音。所以如果有人进入"嘿那里,一切都好吗?" ,所有元音需要打印......但我不知道怎么做? (所以它不是关于计算元音,而是关于打印元音)
现在我已经得到了这个;
sentence = input('Enter your sentence: ' )
if 'a,e,i,o,u' in sentence:
print(???)
else:
print("empty")
答案 0 :(得分:3)
这样的东西?
sentence = input('Enter your sentence: ' )
for letter in sentence:
if letter in 'aeiou':
print(letter)
答案 1 :(得分:1)
如果您想在句子中打印所有元音的出现,这两个答案都很好 - 所以“Hello World”会打印“o”两次等等。
如果你只关心不同的元音,你可以改为循环元音。从某种意义上说,你正在翻转其他答案建议的代码:
sentence = input('Enter your sentence: ')
for vowel in 'aeiou':
if vowel in sentence:
print(vowel)
所以,“嘿那里,一切都好吗?”会打印
a e i
相反:
e e e e e i a i
同样的想法,但遵循Jim的方法将列表理解解压缩到print
:
print(*[v for v in 'aeiou' if v in sentence])
答案 2 :(得分:0)
Supply为func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "teamCell", for: indexPath) as! TeamCell
let view = cell.backgroundCellView
let rectShape = CAShapeLayer()
rectShape.bounds = (view?.frame)!
rectShape.position = (view?.center)!
rectShape.path = UIBezierPath(roundedRect: (view?.bounds)!, byRoundingCorners: [.topRight, .topLeft], cornerRadii: CGSize(width: 20, height: 20)).cgPath
view?.layer.mask = rectShape
view?.layer.masksToBounds = true
return cell
}
提供列表理解并解压缩:
print
这将列出所有元音,并通过解包>>> s = "Hey there, everything allright?" # received from input
>>> print(*[i for i in s if i in 'aeiou'])
e e e e e i a i
将其作为打印调用的位置参数提供。
如果你需要不同的元音,只需提供一套理解:
*
如果您需要添加打印的else子句,请预先构建列表并根据它是否为空来对其执行操作:
print(*{i for i in s if i in 'aeiou'}) # prints i e a
答案 3 :(得分:0)
您可以随时使用RegEx:
import re
sentence = input("Enter your sentence: ")
vowels = re.findall("[aeiou]",sentence.lower())
if len(vowels) == 0:
for i in vowels:
print(i)
else:
print("Empty")
答案 4 :(得分:0)
您始终可以这样做:
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
characters_input = input('Type a sentence: ')
input_list = list(characters_input)
vowels_list = []
for x in input_list:
if x.lower() in vowels:
vowels_list.append(x)
vowels_string = ''.join(vowels_list)
print(vowels_string)
(我也是初学者)