简体   繁体   中英

Join first elements of a list of strings in python3

Consider the following string that represents a line from a tab delimited txt file:

line = 'pf\t2\t0\t9\t0\t9\t9\n'

I would like to join the first two elements from this string using an underscore and then write the line back to file. I am using the following simple script to do it:

newLabel = '_'.join(line.split('\t')[:2])
newLine = line.split('\t')
newLine[:2] = newLabel

What I would expect is the following:

['pf_2', '0', '9', '0', '9', '9\n']

Instead I am getting:

['p', 'f', '_', '2', '0', '9', '0', '9', '9\n']

Maybe I am missing something obvious here but why does python split the joined string again? What is the best way to achieve what I want? Thanks!

You were probably looking for a slightly different assignment statement:

newLine[:2] = [newLabel]

Slice assignment simply expects an iterable on the right hand side. Since newLabel , a string, was an iterable, the slice assignment happily goes and iterates it, adding those elements in place of newLine[:2] .

You might also consider this shortcut:

>>> line.replace('\t', '_', 1)
'pf_2\t0\t9\t0\t9\t9\n'

Using the third argument to str.replace specifies the number of occurences to replace.

First compute the tokens in toks , then rebuild a list using join for 2 first items, and the rest of the list for the rest:

line = 'pf\t2\t0\t9\t0\t9\t9\n'

toks = line.split('\t')
newLine = ["_".join(toks[:2])]+toks[2:]


print(newLine)

result:

['pf_2', '0', '9', '0', '9', '9\n']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM