![](/img/trans.png)
[英]Python: Join all the first elements of list of strings, second elements of list of strings and so on
[英]Join first elements of a list of strings in python3
考慮以下字符串,它代表制表符分隔的txt文件中的一行:
line = 'pf\t2\t0\t9\t0\t9\t9\n'
我想使用下划線將字符串中的前兩個元素連接起來,然后將行寫回到文件中。 我正在使用以下簡單腳本來做到這一點:
newLabel = '_'.join(line.split('\t')[:2])
newLine = line.split('\t')
newLine[:2] = newLabel
我期望的是以下內容:
['pf_2', '0', '9', '0', '9', '9\n']
相反,我得到:
['p', 'f', '_', '2', '0', '9', '0', '9', '9\n']
也許我在這里遺漏了一些明顯的東西,但是為什么python再次拆分連接的字符串? 實現我想要的最好的方法是什么? 謝謝!
您可能正在尋找稍微不同的賦值語句:
newLine[:2] = [newLabel]
切片分配只希望右側有一個可迭代的對象。 由於字符串newLabel
是可迭代的,因此切片分配會愉快地進行迭代,並添加這些元素代替newLine[:2]
。
您可能還會考慮此快捷方式:
>>> line.replace('\t', '_', 1)
'pf_2\t0\t9\t0\t9\t9\n'
在str.replace
使用第三個參數指定要替換的出現次數。
首先計算toks
的令牌,然后使用join
對前兩個項進行重建,然后對其余項進行重建:
line = 'pf\t2\t0\t9\t0\t9\t9\n'
toks = line.split('\t')
newLine = ["_".join(toks[:2])]+toks[2:]
print(newLine)
結果:
['pf_2', '0', '9', '0', '9', '9\n']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.