这个简单的大写字母只写单词而不写句子



我希望它每隔一个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)

最新更新