首页 > 解决方案 > 覆盖或更新列表中的字符串

问题描述

我被赋予了一个简单的任务,即编写代码以大写列表中字符串的奇数索引字符,我对其进行编码如下:

list1 = []
x = int(input("Enter the size of list : "))
for i in range(x):
    temp = str(input("Enter the element you wish to insert : "))
    list1.append(temp)
for i in range(x):
    size = len(list1[i])
    for j in range(size):
        if j%2 == 0:
           list1[i][j].replace(list1[i][j],list1[i][j].upper())
print(list1)

但它似乎不起作用,并且在打印 list1 时它只是返回 list 内的普通字符串。帮助初学者

标签: pythonpython-3.xlist

解决方案


您实际上并不需要内部 for 循环。您可以检查i除以 2 是否等于 1 并替换它。

list1 = []
x = int(input("Enter the size of list : "))
for i in range(x):
    temp = str(input("Enter the element you wish to insert : "))
    list1.append(temp)
for i in range(x):
    if i%2==1:
        list1[i]=list1[i].upper()

print(list1)

例子:

Enter the size of list : 4
Enter the element you wish to insert : a
Enter the element you wish to insert : b
Enter the element you wish to insert : c
Enter the element you wish to insert : d
['a', 'B', 'c', 'D']

如果要更改元素单个字符的大小写,可以执行以下操作:

list1 = []
x = int(input("Enter the size of list : "))
for i in range(x):
    temp = str(input("Enter the element you wish to insert : "))
    list1.append(temp)

for i in range(x):
    list1[i]=''.join(i.upper() if j%2==0 else i for j,i in enumerate(list1[i]))
print(list1)

输出:

Enter the size of list : 3
Enter the element you wish to insert : cat  
Enter the element you wish to insert : hen 
Enter the element you wish to insert : pig
['CaT', 'HeN', 'PiG']

推荐阅读