python - Struggling with slice syntax to join list element of a part of a list -
suppose have simple python list this:
>>> l=['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
now suppose want combine l[2:6]
single element this:
>>> l ['0', '1', '2345', '6', '7', '8', '9']
i able in steps new list, this:
>>> l2=l[0:2] >>> l2.append(''.join(l[2:6])) >>> l2.extend(l[6:]) >>> l2 ['0', '1', '2345', '6', '7', '8', '9']
is there way (that missing) more , in place on original list l
?
edit
as usual, sven marnach had perfect instant answer:
l[2:6] = ["".join(l[2:6])]
i had tried:
l[2:6] = "".join(l[2:6])
but without braces, string produced join treated iterable placing each character in list , reversing join!
consider:
>>> l=['abc','def','ghk','lmn','opq'] >>> l[1:3]=[''.join(l[1:3])] >>> l ['abc', 'defghk', 'lmn', 'opq'] #correct >>> l=['abc','def','ghk','lmn','opq'] >>> l[1:3]=''.join(l[1:3]) >>> l ['abc', 'd', 'e', 'f', 'g', 'h', 'k', 'lmn', 'opq'] #not correct
use slice assignment:
l[2:6] = ["".join(l[2:6])]
Comments
Post a Comment