How to subtract two strings?

后端 未结 8 2026
执笔经年
执笔经年 2020-12-30 00:53

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

相关标签:
8条回答
  • 2020-12-30 01:02

    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

    0 讨论(0)
  • 2020-12-30 01:06

    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)
    
    0 讨论(0)
  • 2020-12-30 01:08

    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"
    
    0 讨论(0)
  • 2020-12-30 01:09

    you could also just do

    print "lamp, bag, mirror".replace("bag,","")
    
    0 讨论(0)
  • 2020-12-30 01:16

    How about this?:

    def substract(a, b):                              
        return "".join(a.rsplit(b))
    
    0 讨论(0)
  • 2020-12-30 01:20

    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)
    
    0 讨论(0)
提交回复
热议问题