目标是以优雅的方式将csv_line
的第二个字段替换为new_item
。这个问题与Rawing列出的主题不同,因为我们正在使用不同的数据结构,尽管我们可以使用其他主题来获得灵感。
# Please assume that csv_line has not been imported from a file.
csv_line = 'unknown_item1,unknown_old_item2,unknown_item3'
new_item = 'unknown_new_item2'
goal = 'unknown_item1,unknown_new_item2,unknown_item3'
# Works but error prone. Non-replaced items could be inadvertently swapped.
# In addition, not convenient if string has many fields.
item1, item2, item3 = csv_line.split(',')
result = ','.join([item1, new_item, item3])
print(result) # unknown_item1,unknown_new_item2,unknown_item3
# Less error prone but ugly.
result_list = []
new_item_idx = 1
for i, item in enumerate(csv_line.split(',')):
result_list += [item] if i != new_item_idx else [new_item]
result = ','.join(result_list)
print(result) # unknown_item1,unknown_new_item2,unknown_item3
# Ideal (not-error prone) but not working.
csv_line.split(',')[1] = new_item
print(csv_line) # unknown_item1,unknown_old_item2,unknown_item3
答案 0 :(得分:3)
可以使用Python的CSV库替换第二项,方法是使用io.StringIO()
个对象。这类似于文件,但可以作为字符串读取:
import csv
import io
csv_line = 'unknown_item1,unknown_old_item2,unknown_item3'
new_item = 'unknown_new_item2'
row = next(csv.reader(io.StringIO(csv_line)))
row[1] = new_item
output = io.StringIO()
csv.writer(output).writerow(row)
goal = output.getvalue()
print(goal)
这会将goal
显示为:
unknown_item1,unknown_new_item2,unknown_item3
答案 1 :(得分:2)
l = csv_line.split(',')
l[1] = new_item
csv_line = ','.join(l)
答案 2 :(得分:1)
在行<div class="flex-container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
中,您根本不会更改csv_line变量。您需要将使用.split()创建的新列表分配给变量,然后才能更改其中的元素:
csv_line.split(',')[1] = new_item
答案 3 :(得分:-1)
这似乎是最pythonic:
csv_line = 'unknown_item1,old_item2,unknown_item3'
old_index = 1
new_item = 'new_item2'
goal = 'unknown_item1,new_item2,unknown_item3'
items = csv_line.split(',')
items[old_index] = new_item
print(','.join(items))
print(goal)
输出:
unknown_item1,new_item2,unknown_item3
unknown_item1,new_item2,unknown_item3