3

Here is my list:

[Volume:vol-b81a2cb0, Volume:vol-ab2b1ba3, Volume:vol-fc2c1cf4]

I want it to look like this:

['vol-b81a2cb0', 'vol-ab2b1ba3', 'vol-fc2c1cf4']

So the following should be done:

  1. The Volume: prefix must be removed from the list elements.
  2. The new elements must be enclosed in single quotes.
1

2 Answers 2

7

try:

strList = map( str, objList)
strList = map( lambda x: x.replace( 'Volume:', ''), strList)
1
  • The first line turns the list of objects to a list of strings representing those objects. Now, how effective this is depends on how the object's class is defined, namely, what the .str (or .display I think) method does. The second line will indeed only work on list of strings.
    – Marek
    Apr 8, 2015 at 7:10
4

You could reduce @Marek code to one line:

strList = list(map(lambda x: str(x).replace('Volume:', ''), strList))

or just use list comprehension:

new_list = [str(i).replace( 'Volume:', '') for i in your_list]

Since Python 3.9 you can use removeprefix() function what will simplify your code even more:

new_list = [str(i).removeprefix('Volume:') for i in your_list]

More info about removeprefix(): PEP 616

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.