我希望它每隔一个leter:JuSt LiKe tHiS
就大写一次,但不要处理长句
def capitalise():
x=input("enter the word= ")
a=0
while a < len(x):
if x[a].islower():
x = x[:a] + x[a].upper() + x[a+1:]
a = a + 2
print (x)
将增量移出if
子句,否则它将保留在while
循环中:
def capitalise():
x = input("enter the word= ")
a = 0
while a < len(x):
if x[a].islower():
x = x[:a] + x[a].upper() + x[a + 1:]
a = a + 2 # this line changed
print(x)
一种更有效的方法(还有一点pythonic(是使用枚举对字符进行迭代,如下所示:
def capitalise():
x = input("enter the word= ")
characters = list(x)
result = "".join([c.upper() if i % 2 == 0 else c for i, c in enumerate(characters)])
print(result)