python字符串与列表_Python字符串和列表

本文介绍了一个字符串处理的问题:从句子中的每个单词找到第一个元音字母,删除该元音后的所有字母,并将剩余部分重复三次。作者提供了初始代码及遇到的问题,并分享了一个有效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Been sitting on this minor problem a few days now, I don't know if I have it all wrong or just missed out on something.

The Objective: From each word in a sentence - Find the first vowel, remove the letters after that vowel from the word and multiply the remaining letters by 3.

The Example: If I have the sentence: "Hello World" the wanted output should be "HeHeHe WoWoWo".

My Code:

def bebis(inrad):

utrad = ""

inrad = inrad.split()

for tkn in inrad:

for tkn1 in tkn: #Eftersom tkn ar ordlista nu.

if tkn1 in vokaler:

count = len(tkn1)

utrad += tkn1

elif tkn1 in konsonanter:

utrad += tkn1

return utrad[:count+1]*3

print("Bebisspraket:",bebis(inrad))

My Thoughts: I split the sentence into a lists of words using split(). Then I use two for loops, one that should go through each word and the other one that should go through each letter in every word. If it finds a vowel, count where it is and then return the letters to the first vowel of the word.

My Problem: The output only gives me the first WORD in a sentence and breaks from there. So "Hello World" yields "HeHeHe" leaving me super frustrated. Why does it not go through the rest of the sentence?

解决方案

How about something like this:

import re

def bebis_word(word):

first_vowel = re.search("[aeiou]", word, re.IGNORECASE)

if first_vowel:

return word[0:first_vowel.start() + 1] * 3

else:

return ''

def bebis(sentence):

words = [bebis_word(word) for word in sentence.split()]

return " ".join(words)

print bebis("Hello World")

Output:

HeHeHe WoWoWo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值