25

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.

4

8 回答 8

43

你也可以这样做

print "lamp, bag, mirror".replace("bag,","")
于 2013-08-26T23:28:39.233 回答
32

这个怎么样?

def substract(a, b):                              
    return "".join(a.rsplit(b))
于 2014-04-29T23:10:00.990 回答
12

只要您使用格式正确的列表,您就可以这样做:

s0 = "lamp, bag, mirror"
s = s0.split(", ") # s is a list: ["lamp", "bag", "mirror"]

如果列表格式不正确,您可以按照@Lattyware 的建议执行以下操作:

s = [item.strip() for item in s0.split(',')]

现在删除元素:

s.remove("bag")
s
=> ["lamp", "mirror"]

无论哪种方式 - 要重建字符串,请使用join()

", ".join(s)
=> "lamp, mirror"

另一种方法是使用replace()- 但要小心要替换的字符串,例如"mirror"末尾没有尾随,

s0 = "lamp, bag, mirror"
s0.replace("bag, ", "")
=> "lamp, mirror"
于 2013-08-26T23:21:21.093 回答
1

您应该将您的字符串转换为字符串列表,然后执行您想要的操作。看

my_list="lamp, bag, mirror".split(',')
my_list.remove('bag')
my_str = ",".join(my_list)
于 2013-08-26T23:22:09.250 回答
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. 
于 2018-12-30T14:24:44.637 回答
1

如果您有两个字符串,如下所示:

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

并且您想减去这两个字符串,那么您可以使用以下代码:

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

输出将如下所示:

你是他吗

于 2015-12-21T07:01:31.067 回答
0

使用正则表达式示例:

import re

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

pattern = re.compile("[^\w]+")
result = pattern.split(text)
result.remove(word)
print ", ".join(result)
于 2013-08-26T23:29:44.997 回答
0

使用以下内容,您可以添加更多要删除的单词 ( ["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"
于 2017-10-18T09:52:53.453 回答