Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 689
Louis Avatar asked Jul 04 '12 09:07

Louis


People also ask

How do you truncate a string to a specific length in Python?

The syntax of rsplit() is rsplit(delimiter)[length to truncate]. The 'delimiter' is the separator value based on which the string will be divided into parts. The 'length to truncate' is the number at which the word exists in the string.

How do you limit the length of a text in Python?

Use syntax string[x:y] to slice a string starting from index x up to but not including the character at index y. If you want only to cut the string to length in python use only string[: length].


2 Answers

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']
like image 164
ThiefMaster Avatar answered Oct 21 '22 23:10

ThiefMaster


Use a list comprehension:

[elem[:12] for elem in g]
like image 41
ecatmur Avatar answered Oct 22 '22 00:10

ecatmur