Python字符串和列表 [英] Python string and lists

查看:126
本文介绍了Python字符串和列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天前坐在这个小问题上,我不知道自己是错了还是错过了什么.

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.

目标:从句子中的每个单词-找到第一个元音,从单词中删除该元音之后的字母,然后将其余字母乘以3.

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.

示例:如果我有一句话:"Hello World",所需的输出应该是"HeHeHe WoWoWo".

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

我的代码:

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))

我的想法:我使用split()将句子分成单词列表.然后,我使用两个for循环,一个循环应遍历每个单词,另一个循环应遍历每个单词的每个字母.如果找到元音,请数一数,然后将字母返回到单词的第一个元音.

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.

我的问题:输出仅给我一个句子中的第一个单词,并从那里中断.因此,"Hello World"产生了"HeHeHe",这让我非常沮丧.为什么它没有贯穿句子的其余部分?

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?

推荐答案

这样的事情如何?

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")

输出:

呵呵呵窝窝

HeHeHe WoWoWo

这篇关于Python字符串和列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆