简体   繁体   English

Python-替换字符串列表中的字符

[英]Python - Replacing chars within list of strings

I am trying to remove the chars '0' from chars 2 to 3 of each item in the following list: 我正在尝试从以下列表中每个项目的字符2到3中删除字符“ 0”:

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. 在Python中,字符串(字节或Unicode)是不可变的。 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) (您不能在整个字符串中替换'0' ,因为您要保留初始的一个)


To insist on mutability: above code modifies list1, while this: 坚持可变性:上面的代码修改了 list1,同时:

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. 因为列表已被修改,所以list2指向修改后的列表。 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. 因为list1是一个新列表,而list2仍引用原始列表。

You can use re.sub : 您可以使用re.sub

import re
list1 = ['0x001', '0x002', '0x0a3']
new_result = [re.sub('(?<=x)[0]+', '', i) for i in list1]

Output: 输出:

['0x1', '0x2', '0xa3']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM