Consider the following string that represents a line from a tab delimited txt file:
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']
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
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.