I am trying to remove the chars '0' from chars 2 to 3 of each item in the following list:
list1 = ['0x001', '0x002', '0x0a3']
my desired output is:
list1 = ['0x1', '0x2', '0xa3']
this is the way I have tried so far but has not worked:
for i in list1:
if i[2:3] == '0':
i.replace('0', '')
But this makes no changes to the items in the list. Thank you in advance!
In Python, a string (be it byte or unicode) is immutable. That means that you cannot change it, you can only have the variable to reference a new value.
A list is a mutable object so you can change its individual elements.
Here you could do:
for index, i in enumerate(list1):
if i[2:3] == '0':
list1[index] = i[:2] + i[2:].replace('0', '')
(you cannot replace '0'
in the whole string because you want to preserve the initial one)
To insist on mutability: above code modifies list1, while this:
list1 = [ i[:2] + i[2:].replace('0', '') for i in list1 ]
will create a new list.
Just look at those 2 example codes:
list1 = ['0x001', '0x002', '0x0a3']
list2 = list1
for index, i in enumerate(list1):
if i[2:3] == '0':
list1[index] = i[:2] + i[2:].replace('0', '')
print(list1, list2)
output is:
['0x1', '0x2', '0xa3'] ['0x1', '0x2', '0xa3']
because the list has been modified, so list2
points the the modified list. But with
list1 = ['0x001', '0x002', '0x0a3']
list2 = list1
list1 = [ i[:2] + i[2:].replace('0', '') for i in list1 ]
print(list1, list2)
output is:
['0x1', '0x2', '0xa3'] ['0x001', '0x002', '0x0a3']
because list1
is a new list while list2
still references the original one.
You can use re.sub
:
import re
list1 = ['0x001', '0x002', '0x0a3']
new_result = [re.sub('(?<=x)[0]+', '', i) for i in list1]
Output:
['0x1', '0x2', '0xa3']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.