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?
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.
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].
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']
Use a list comprehension:
[elem[:12] for elem in g]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With