该代码为每个偶数均以大写字母打印字符串。 我通过索引计数器(index = 0)检查了每个字符的索引。 还有其他选择来查找索引吗?没有肌酸指数计数?
def myfunc(str):
index = 0
low = str.lower()
new_str = ''
for char in str:
if index % 2 == 0:
new_str += char.upper()
else:
new_str += char
index += 1
return new_str
print(myfunc('Hello World'))
答案 0 :(得分:0)
尝试使用:
HeLlO WoRlD
输出:
def myfunc(str):
new_str = ''
for index,char in enumerate(str):
if index % 2 == 0:
new_str += char.upper()
else:
new_str += char
return new_str
print(myfunc('Hello World'))
答案 1 :(得分:0)
答案 2 :(得分:0)
def myfunc(str_string): # Dont use the str, its a keyword
str_string = str_string.lower()
new_str = ''
for index in range(len(str_string)): # loop through the string length rather string itself
if index % 2 == 0:
new_str += str_string[index].upper()
else:
new_str += str_string[index]
index += 1
return new_str
print(myfunc('Hello World'))
# one liner
str_index = 'Hello World'
print("".join([str_index[i].upper() if i%2==0 else str_index[i].lower() for i in range(len(str_index)) ]))