Skip to content
Advertisement

How to strip only specific parts of a list element in Python

So lets say i have a list, where one element contains an ‘hour-minute-second-tagnumber’, like this:

mylist = ['10 30 12 TTH-312', '10 38 45 ZHE-968', '11 25 54 KAP-116']

How do I make this of an element: '103012 TTH-312'?

Can I .strip only specific parts of an element somehow?

Advertisement

Answer

You can limit the number of replace to 2.

[x.replace(' ','', 2) for x in mylist]

Output

['103012 TTH-312', '103845 ZHE-968', '112554 KAP-116']

If you are trying to do a loop:

adatok = ['10 30 12 TTH-312', '10 38 45 ZHE-968', '11 25 54 KAP-116']
for i in adatok: 
    i = i.replace(' ','', 2) 
    print(i)
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement