SpyTh SpyTh - 1 year ago 108
Python Question

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?

wim wim
Answer Source

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)

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download