gpt4 book ai didi

python 3 : Change one character of item in list

转载 作者:太空宇宙 更新时间:2023-11-04 08:38:08 25 4
gpt4 key购买 nike

我有一个这样的列表:

['ID|number1|number2|+|name|location','ID2|number3|number4|-|name2|location2']

该列表是从字典生成的,并包含字典的键。我想改变第一个'|'变成一个“=”。

我试过这个:

keyList=[]
for item in finalDict.keys():
keyList.append(item)

z=0
for item in keyList:
for letter in item:
if letter=='|':
z+=1
if z==1:
letter.replace('|', '=')

但我没有得到错误或我想要的输出

Actual output:
['ID|number1|number2|+|name|location','ID2|number3|number4|-|name2|location2']


Desired output:
['ID=number1|number2|+|name|location','ID2=number3|number4|-|name2|location2']

最佳答案

to change the first '|' into a '='

简单来说:

keyList = ['ID|number1|number2|+|name|location','ID2|number3|number4|-|name2|location2']
result = [k.replace('|', '=', 1) for k in keyList]

print(result)

输出:

['ID=number1|number2|+|name|location', 'ID2=number3|number4|-|name2|location2']

  • str.replace(old, new[, count]) - 如果可选参数 count 是 给定,只有第一个出现的次数被替换。

关于 python 3 : Change one character of item in list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47134099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com