Python双循环中所有字符串的大写
我有以下 Python 代码,它循环遍历字符串并将每个字符大写:
str = 'abcd'
l = list(str)
for i in range(len(l)):
rl = list(str)
cap_char = l[i].capitalize()
rl[i] = cap_char
str1 = ''.join(rl)
print str1
生成:
Abcd aBcd abCd abcD
我想增强此代码以增加受大写限制的连续字符的数量,直到该数量达到 len(l) - 1 以产生:
Abcd aBcd abCd abcD >> - 1 char capitalized
ABcd aBCd abCD AbcD >> - 2 chars capitalized
ABCd aBCD AbCD ABcD >> - 3 chars capitalized
当我进行索引算术时,我遇到“索引超出范围”错误,理解 idices 应该换行,但似乎无法生成优雅的代码;(
I have the following Python code, that cycles thru the string and capitalizes each character:
str = 'abcd'
l = list(str)
for i in range(len(l)):
rl = list(str)
cap_char = l[i].capitalize()
rl[i] = cap_char
str1 = ''.join(rl)
print str1
Which produces:
Abcd aBcd abCd abcD
I would like to enhance this code to increment number of successive characters subject to capitalization until such number reaches len(l) - 1 to produce:
Abcd aBcd abCd abcD >> - 1 char capitalized
ABcd aBCd abCD AbcD >> - 2 chars capitalized
ABCd aBCD AbCD ABcD >> - 3 chars capitalized
I am running into "index out of range" errors when I do index arithmetic, understand idices should wrap, but can't seem to produce an elegant code ;(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
输出:
Output:
在计算索引号时使用模运算符:
顺便说一句,不要使用
str
作为 python 中的变量名称。要了解原因,请尝试以下操作:use modulo operator while computing index number:
BTW, do not use
str
as a varaible name in python. To understand why, try this:根据您对 wim 问题的回答,您要么想要 wim 的答案 或这个:
编辑:当然,如果你想循环这个:
Depending on your answer to wim's question, you either want wim's answer or this:
EDIT: And, of course, if you want to loop over this: