26

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, in other programming languages I can easily do: str=str-"bag," and get str="lamp, mirror," this doesnt work in python (I'm using 2.7 on a W8 pc)

Is there a way to split the string across say "bag," and somehow use that as a subtraction? Then I still need to figure out how to add.

martineau
  • 119,623
  • 25
  • 170
  • 301
max smith
  • 273
  • 1
  • 3
  • 4
  • 1
    When you say 'subtract', do you mean remove an item from your list, or remove the last characters if they match (and if they don't, what should the behaviour be? What about duplicate values? – Gareth Latty Aug 26 '13 at 23:20
  • 1
    Take a look at string replace: http://docs.python.org/2/library/string.html#string.replace – kevmo314 Aug 26 '13 at 23:21
  • 14
    `in other programming languages i can easily do: str=str-"bag," and get str="lamp, mirror," ` what languages? – Joran Beasley Aug 26 '13 at 23:27
  • That was an assumption. I thaugh it was possible in VBS and Java no? – max smith Aug 28 '13 at 22:35

8 Answers8

45

you could also just do

print "lamp, bag, mirror".replace("bag,","")
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • 3
    Of course, this functions differently to other examples in the case of duplicates - the OP doesn't give any explanation of the required behaviour in that case, but it's worth a note. – Gareth Latty Aug 26 '13 at 23:31
  • 1
    good point ... really the split is probably the "correct" answer, however I figured I would throw this out there. not sure what languages support string subtraction or how it would behave in said languages – Joran Beasley Aug 26 '13 at 23:33
32

How about this?

def substract(a, b):                              
    return "".join(a.rsplit(b))
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
Zaka Elab
  • 576
  • 5
  • 14
12

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"
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • It might be worth mentioning `str.split()`. – Gareth Latty Aug 26 '13 at 23:21
  • Yep, I was about to do that :) – Óscar López Aug 26 '13 at 23:23
  • 2
    Obviously, there is an assumption here that the list is well-formed with spaces after each item, if that is not the case, the `[item.strip() for item in s0.split(',')]` is more flexible (a simple [list comprehension](http://www.youtube.com/watch?v=pShL9DCSIUw) with the [`str.strip()`](http://docs.python.org/3/library/stdtypes.html#str.strip) method). – Gareth Latty Aug 26 '13 at 23:25
1

you should convert your string to a list of string then do what you want. look

my_list="lamp, bag, mirror".split(',')
my_list.remove('bag')
my_str = ",".join(my_list)
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
dare
  • 662
  • 1
  • 6
  • 15
1

If you have two strings like below:

t1 = 'how are you'
t2 = 'How is he'

and you want to subtract these two strings then you can use the below code:

l1 = t1.lower().split()
l2 = t2.lower().split()
s1 = ""
s2 = ""
for i in l1:
  if i not in l2:
    s1 = s1 + " " + i 
for j in l2:
  if j not in l1:
    s2 = s2 + " " + j 

new = s1 + " " + s2
print new

Output will be like:

are you is he

Rohan Amrute
  • 764
  • 1
  • 9
  • 23
1
from re import sub

def Str2MinusStr1 (str1, str2, n=1) :
    return sub(r'%s' % (str2), '', str1, n)

Str2MinusStr1 ('aabbaa', 'a')  
# result 'abbaa'

Str2MinusStr1 ('aabbaa', 'ab')  
# result 'abaa'

Str2MinusStr1 ('aabbaa', 'a', 0)  
# result 'bb'

# n = number of occurences. 
# 0 means all, else means n of occurences. 
# str2 can be any regular expression. 
Dengs
  • 11
  • 2
0

Using regular expression example:

import re

text = "lamp, bag, mirror"
word = "bag"

pattern = re.compile("[^\w]+")
result = pattern.split(text)
result.remove(word)
print ", ".join(result)
badc0re
  • 3,333
  • 6
  • 30
  • 46
0

Using the following you can add more words to remove (["bag", "mirror", ...])

(s0, to_remove) = ("lamp, bag, mirror", ["bag"])
s0 = ", ".join([x for x in s0.split(", ") if x not in to_remove])
=> "lamp, mirror"
J. Doe
  • 3,458
  • 2
  • 24
  • 42