首页 > 解决方案 > 在 Python 中迭代字符串索引时遇到问题

问题描述

我希望 Python 获取一个字符串并遍历它,打印几个变体,其中单个字母大写。像这样:

输入:

“你好世界”

输出:

“你好世界”、“你好世界”、“你好世界”等。

这是我到目前为止所拥有的:

string = "hello world".lower()
for x in range(0, len(string)):
    new_string = string[:(x-1)].lower() + string[x].capitalize() + string[(x-1):].lower()
    print(new_string)

然而,这段代码吐出了一些看起来很时髦的字符串:

hello worlHd
Ehello world
hLello world
etc.

我怀疑我的问题与我索引字符串的方式有关,但我不确定要更改什么。有任何想法吗?

标签: pythonstringloops

解决方案


这是一个简单的更改,应该使它与您的语法一起使用。

for i in range(len(string)):
    print(string[:i] + string[i].upper() + string[i+1:])

输出:

Hello world
hEllo world
heLlo world
helLo world
hellO world
hello world
hello World
hello wOrld
hello woRld
hello worLd
hello worlD

还有其他方法可以做到这一点,但这个方法很容易理解。

PS:也可以在左右两边加上.lower()。这完全取决于您使用的输入。


推荐阅读