如何在Python中修复此字符串问题?

时间:2012-09-23 21:26:51

标签: python string loops

我正在尝试使用某些单词(不是像ie或ei这样的连续元音)添加带元音的文本,例如:

字:'怪异'

在元音之前添加的文字:'ib'

结果:'wibeird'

因此,在元音'e'之前添加了文本'ib'。请注意它是如何不用'ib'替换'i'的,因为当元音连续时我不希望它添加文本。

然而,当我这样做时:

字:'狗'

在元音之前添加的文字:'ob'

结果:'doboog'

正确的结果应该是:'dobog'

我一直在尝试调试我的程序,但我似乎无法弄清楚逻辑,以确保它正确打印'wibeird'和'dobog'。

这是我的代码,先用'ob'代替first_syl,用'dog'代替'dog'代替'。

first_syl = 'ib'
word = 'weird'

vowels = "aeiouAEIOU"
diction = "bcdfghjklmnpqrstvwxyz"
empty_str = ""
word_str = ""
ch_str = ""
first_vowel_count = True

for ch in word:
    if ch in diction:
        word_str += ch
    if ch in vowels and first_vowel_count == True:
        empty_str += word_str + first_syl + ch
        word_str = ""
        first_vowel_count = False
    if ch in vowels and first_vowel_count == False:
        ch_str = ch
    if word[-1] not in vowels:
        final_str = empty_str + ch_str + word_str 

print (final_str)

我正在使用Python 3.2.3。另外我不想使用任何导入的模块,尝试这样做是为了理解python中字符串和循环的基础知识。

2 个答案:

答案 0 :(得分:2)

您是否考虑过正则表达式?

import re

print (re.sub(r'(?<![aeiou])[aeiou]', r'ib\g<0>', 'weird')) #wibeird
print (re.sub(r'(?<![aeiou])[aeiou]', r'ob\g<0>', 'dog')) #dobog

答案 1 :(得分:1)

不必使用正则表达式。有一句名言

  

有些人在面对问题时会思考   “我知道,我会使用正则表达式。”现在他们有两个问题。

这可以通过基本的if-then语句轻松解决。这是一个注释版本,解释了所使用的逻辑:

first_syl = 'ib' # the characters to be added
word = 'dOg'     # the input word

vowels = "aeiou" # instead of a long list of possibilities, we'll use the 
                 # <string>.lower() func. It returns the lowercase equivalent of a 
                 # string object.
first_vowel_count = True # This will tell us if the iterator is at the first vowel
final_str = ""           # The output.

for ch in word:
    if ch.lower() not in vowels:     # If we're at a consonant, 
        first_vowel_count = True     # the next vowel to appear must be the first in 
                                     # the series.

    elif first_vowel_count:          # So the previous "if" statement was false. We're 
                                     # at a vowel. This is also the first vowel in the 
                                     # series. This means that before appending the vowel 
                                     # to output, 

        final_str += first_syl       # we need to first append the vowel-
                                     # predecessor string, or 'ib' in this case.
        first_vowel_count = False    # Additionally, any vowels following this one cannot 
                                     # be the first in the series.

    final_str += ch                  # Finally, we'll append the input character to the 
                                     # output.
print(final_str)                     # "dibOg"