我有一个如下列表:
days = ['monday', 'tuesday', 'wednesday', 'thursday']
我希望print
这个:
Monday # 1 uppercase letter
TUesday # 2 uppercase letters
WEDnesday # ...
THURsday
这是我到目前为止所做的:
for day in days:
print day[0].upper() = day[1:]
打印:
Monday
Tuesday
Wednesday
Thursday
如何获得所需的结果?
答案 0 :(得分:2)
你可能已经尝试了一点,因为你越来越近了。看看这个:
days = ['monday', 'tuesday', 'wednesday', 'thursday']
for i, day in enumerate(days):
print(day[:i+1].upper() + day[i+1:])
或者简单地说:
print('\n'.join([x[:i+1].upper() + x[i+1:] for i, x in enumerate(days)]))
他们print
所需的:
Monday
TUesday
WEDnesday
THURsday
答案 1 :(得分:1)
字符串在python中是不可变的,因此您必须创建一个新字符串:
list_1 = ['monday', 'tuesday', 'wednesday', 'thursday']
list_2 = []
for i, day in enumerate(list_1):
list_2.append(day[:i+1].upper() + day[i+1:].lower())
print(list_2)
您可以使用相同的列表,我使用不同的列表来说明它们是不同的字符串。
输出:
['Monday', 'TUesday', 'WEDnesday', 'THURsday']
答案 2 :(得分:1)
最简单的方法:
days = ['monday', 'tuesday', 'wednesday', 'thursday']
number = 1
for day in days:
print(day[:number].upper()+day[number:])
number +=1
答案 3 :(得分:0)
也可以试试这个:
days = ['monday', 'tuesday', 'wednesday', 'thursday']
result = [day[:i].upper() + day[i:] for day, i in zip(days, range(1, len(days) + 1))]
print('\n'.join(result))
# Monday
# TUesday
# WEDnesday
# THURsday