我有一个这样的清单:
['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']
答案 0 :(得分:3)
改变第一个'|'进入'='
以简单的方式:
changeDetector.detach()
输出:
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])
是
给定,只替换第一次计数。答案 1 :(得分:2)
l=['ID|number1|number2|+|name|location','ID2|number3|number4|-|name2|location2']
j=[]
for i in l:
i=i.replace("|","=",1)
j.append(i)
print(j)
输出
['ID=number1|number2|+|name|location', 'ID2=number3|number4|-|name2|location2']
答案 2 :(得分:0)
使用list comprehesion + regex
import re
theList=['ID|number1|number2|+|name|location','ID2|number3|number4|-|name2|location2']
print [ re.sub(r'(ID.?)\|',r'\1=',item) for item in theList]