I have a long string, which is basically a list like str=\"lamp, bag, mirror,\"
(and other items)
I was wondering if I can add or subtract some items, i
You can do this as long as you use well-formed lists:
s0 = "lamp, bag, mirror"
s = s0.split(", ") # s is a list: ["lamp", "bag", "mirror"]
If the list is not well-formed, you can do as follows, as suggested by @Lattyware:
s = [item.strip() for item in s0.split(',')]
Now to delete the element:
s.remove("bag")
s
=> ["lamp", "mirror"]
Either way - to reconstruct the string, use join()
:
", ".join(s)
=> "lamp, mirror"
A different approach would be to use replace()
- but be careful with the string you want to replace, for example "mirror"
doesn't have a trailing ,
at the end.
s0 = "lamp, bag, mirror"
s0.replace("bag, ", "")
=> "lamp, mirror"