没有反向功能的反向字符串

时间:2016-11-26 00:06:06

标签: python string python-3.x

对于输入文本,我必须计算所有元音,将每个单词中的首字母大写并反向输出文本(不必大写),而不使用标题或反向函数。我能够弄清楚元音的数量,但与其他两个人挣扎。

universal_newlines=True

1 个答案:

答案 0 :(得分:3)

以下是两个反转字符串的示例。 切片串

>>> s = 'hello'
>>> reversed_s = s[::-1]

或循环。

res = ''
for char in s:
    res = char + res

完整代码

def main():
    # Run infinitely until break or return
    # it's more elegant to do a while loop this way with a condition to
    # break instead of setting an initial variable with random value.
    while True:
        text = input('Please enter some text or press <ENTER> to exit: ')
        # if nothing is entered then break
        if not text:
            break

        vowelCount = 0
        res = ''
        prev_letter = None

        for char in text:
            if char.lower() in 'aeiou':
                vowelCount += 1
            # If previous letter was a space or it is the first letter
            # then capitalise it.
            if prev_letter == ' ' or prev_letter is None:
                char = char.upper()

            res += char # add char to result string
            prev_letter = char # update prev_letter

        print(res) # capitalised string
        print(res[::-1]) # reverse the string
        print('Vowel Count is: {0}'.format(vowelCount))

# Example
Please enter some text or press <ENTER> to exit: hello world!
Hello World!
!dlroW olleH
Vowel Count is: 3