简体   繁体   English

如何仅替换列表的特定部分?

[英]How to replace only a certain part of a list?

How do I replace apple in the beginning of each string in the list to orange? 如何将列表中每个字符串开头的apple替换为orange?

Here is what I have tried: 这是我尝试过的:

appleList = ['apple_00', 'apple_01', 'apple_02', 'apple_03']

appleList = ['orange' if 'apple' in appleList]

print appleList

Output: ['apple_00', 'apple_01', 'apple_02', 'apple_03'] 输出: ['apple_00', 'apple_01', 'apple_02', 'apple_03']

Desired Output: ['orange_00', 'orange_01', 'orange_02', 'orange_03'] 所需的输出: ['orange_00', 'orange_01', 'orange_02', 'orange_03']

You should use the replace method to modify the strings inside the list: 您应该使用replace方法来修改列表中的字符串:

>>> my_list = ['Apple_00', 'Apple_01', 'Apple_02', 'Apple_03']
>>> print([s.replace('Apple', 'Orange') for s in my_list])

this will print 这将打印

['Orange_00', 'Orange_01', 'Orange_02', 'Orange_03']

As a side note, you should really use lowercase names for variables per Python Style Guide - PEP08 . 附带说明一下,您确实应该根据《 Python样式指南-PEP08》对变量使用小写名称。

Use replace when an item contains Apple . 当项目包含Apple时,请使用replace

This does it: 这样做:

r = [x.replace('Apple', 'Orange') for x in Register]

print(r)
# ['Orange_00', 'Orange_01', 'Orange_02', 'Orange_03']

You're checking if certain elements in the list are the string 'Apple' , which is obviously never True . 您正在检查列表中的某些元素是否为字符串'Apple' ,这显然不是True you can do it like this: 您可以这样做:

Register = ['Apple_00', 'Apple_01', 'Apple_02', 'Apple_03']
New_Register = []

for entry in Register:
    New_Register.append(entry.replace('Apple', 'Orange'))

print Register
print New_Register

Or you just use a list comprehension: 或者您只使用列表理解:

Register = ['Apple_00', 'Apple_01', 'Apple_02', 'Apple_03']
Register = [x.replace('Apple', 'Orange') for x in Register]

print Register

Hope this helps! 希望这可以帮助!

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

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