python - 覆盖或更新列表中的字符串
问题描述
我被赋予了一个简单的任务,即编写代码以大写列表中字符串的奇数索引字符,我对其进行编码如下:
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 内的普通字符串。帮助初学者
解决方案
您实际上并不需要内部 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']
推荐阅读
- sql - 你能交叉加入一个查询的结果吗
- python - Azure 事件中心 - ImportError:没有名为 eventhubs 的模块
- angular - 使上下文可用于传递给 ng-content 的模板
- python - 比较 2 个 csv 文件之间的列并使用 Python 编写差异
- reactjs - 在 React 中声明静态数据的最佳位置/方式
- scala - 优化 Spark Couchbase 连接器上的提取大小
- python - 在谷歌云平台上不断运行python
- c# - 对于 DependencyProperty 值,是否有类似于 RegisterClassHandler 的方法?
- ios - 从 UIImagePickerController 中选择后如何删除本地视频文件?
- visual-studio-app-center - 应用中心电子邮件安装是否适用于 32 位设备,尤其是 iPhone 5c?