簡體   English   中英

我如何在python中減去兩個字符串?

[英]How can i subtract two strings in python?

我有一個很長的字符串,基本上是一個像str="lamp, bag, mirror," (和其他項目)的列表

我想知道我是否可以添加或減去一些項目,在其他編程語言中我可以輕松做到: str=str-"bag,"並獲得str="lamp, mirror,"這在python中不起作用(我使用的是2.7)在W8電腦上)

有沒有辦法將字符串分開說“bag”,並以某種方式將其用作減法? 然后我仍然需要弄清楚如何添加。

你也可以這樣做

print "lamp, bag, mirror".replace("bag,","")

這個怎么樣?:

def substract(a, b):                              
    return "".join(a.rsplit(b))

只要您使用格式良好的列表,就可以執行此操作:

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"

你應該將你的字符串轉換為字符串列表然后做你想要的。

my_list="lamp, bag, mirror".split(',')
my_list.remove('bag')
my_str = ",".join(my_list)

如果你有兩個字符串如下:

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

輸出將如下:

你是他嗎?

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. 

使用正則表達式示例:

import re

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

pattern = re.compile("[^\w]+")
result = pattern.split(text)
result.remove(word)
print ", ".join(result)

使用以下內容,您可以添加更多要刪除的單詞( ["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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM