Louis
Louis

Reputation: 2900

How to truncate all strings in a list to a same length, in some pythonic way?

Let's say we have a list such as:

g = ["123456789123456789123456", 
     "1234567894678945678978998879879898798797", 
     "6546546564656565656565655656565655656"]

I need the first twelve chars of each element :

["123456789123", 
 "123456789467", 
 "654654656465"]

Okay, I can build a second list in a for loop, something like this:

g2 = []
for elem in g:
    g2.append(elem[:12])

but I'm pretty sure there are much better ways and can't figure them out for now. Any ideas?

Upvotes: 13

Views: 12269

Answers (3)

zenpoy
zenpoy

Reputation: 20136

Another option is to use map(...) :

b = map(lambda x: x[:9],g)

Upvotes: 5

ecatmur
ecatmur

Reputation: 157514

Use a list comprehension:

[elem[:12] for elem in g]

Upvotes: 6

ThiefMaster
ThiefMaster

Reputation: 318808

Use a list comprehension:

g2 = [elem[:12] for elem in g]

If you prefer to edit g in-place, use the slice assignment syntax with a generator expression:

g[:] = (elem[:12] for elem in g)

Demo:

>>> g = ['abc', 'defg', 'lolololol']
>>> g[:] = (elem[:2] for elem in g)
>>> g
['ab', 'de', 'lo']

Upvotes: 20

Related Questions