python - 没有反转功能的反转字符串

标签 python string python-3.x

对于输入文本,我必须计算所有元音,将每个单词中的第一个字母大写并反向输出文本(不必大写),而不使用标题或反向函数。我能够计算出元音的数量,但计算出其他两个元音的数量却很困难。

def main():

    vowelCount = 0
    text = 'abc'

    while(len(text) != 0):
        text = input('Please etner some text or press <ENTER> to exit: ')

        for char in text:
            if char in 'aeiouAEIOU':
                vowelCount += 1
        print('Vowels:', vowelCount)
        vowelCount = 0



        for i in text:
            i = text.find('') + 1
        print(i)

        print(text[0].upper() + text[1:])


main()   

最佳答案

下面是两个反转字符串的示例。 对字符串进行切片

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

关于python - 没有反转功能的反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40813675/

相关文章:

python-3.x - Pandas操作,将多个结果放入df列

python - 使用 Dicts 设置 DataFrame,意外设置

python - 为 Python 包添加虚拟命名空间

c++ - 一些 C++ vector 问题

java - 如何在 Java 中比较字符串?

python - pickle 后如何更改类方法的定义

python - 如何将Figure对象转换为具有RGBA值的Numpy数组?

也可以充当客户端的Python服务器

javascript - 从 URL 捕获顶级域名时出现问题

python - 如何在Open CV Python中消除这些噪音?