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 firs
Solution 1:
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']
Solution 2:
Use a list comprehension:
[elem[:12] for elem in g]
Solution 3:
Another option is to use map(...)
:
b = map(lambda x: x[:9],g)
Post a Comment for "How To Truncate All Strings In A List To A Same Length, In Some Pythonic Way?"