python - 在 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.
我怀疑我的问题与我索引字符串的方式有关,但我不确定要更改什么。有任何想法吗?
解决方案
这是一个简单的更改,应该使它与您的语法一起使用。
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()。这完全取决于您使用的输入。
推荐阅读
- python - 确定每掷骰子的几率
- javascript - 从 ts 文件导出多个 typescript 类型别名时出现错误“Unexpected token”
- python - 尝试发布 to_do 项目时的 Python + Django URL 和查看错误
- node.js - 在被邀请到服务器后,我似乎找不到让我的不和谐机器人发送消息的方法
- excel - VBA PRNG 有偏见吗?
- node.js - 在结帐时条纹默认卡
- c++ - GlobalAlloc 代替其他分配方式
- r - 从 R 数据帧中采样
- javascript - 使用 Dropify 删除上传的图片
- javascript - Reduce() 到状态对象 Typescript