如何从字符串列表中删除特定的子字符串?

2024-06-10 09:56:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两张单子

y1=['fem j sex / male \n', "  father's name  diwan singh saggu   \n", "elector's name   rahul saggu \n", 'identity card \n', 'zfk0281501', 'age as on 1.1.2008   23 \n']

word=["sex","father's","name","elector's","name","identity","card","age"]

我需要删除y1中的所有字符串,它位于word中。 我需要输出为

^{pr2}$

我在y1中分解了各个元素,并尝试将其与字。但是我不知道下一步该怎么办?如何去掉绳子??我试过了

y1new=[]
for y in y1:
    tmp=y.split()
    y1new.append(tmp)
for i in y1new:
    for j in i:
        if j in word:
            y1new[i].remove(y1new[i][j])

我怎样才能做到这一点?在


Tags: nameinforagecardtmpidentityword
3条回答

试试这个程序!在

它会完美工作的! 另外,我附上了程序的输出。在

y1=['fem j sex / male \n', "  father's name  diwan singh saggu   \n", "elector's name   rahul saggu \n", 'identity card \n', 'zfk0281501', 'age as on 1.1.2008   23 \n']
word=["sex","father's","name","elector's","identity","card","age","\n"]

output =[]            //output list
for i in range(0,len(y1)): 
  for j in range(0,len(word)):
    a=y1[i].find(word[j])           //finds the word in a y1 list , if it found & returns index greater than -1 than replace the substring in a y1 list with empty string ' '
    if a!=-1:
      y1[i]=y1[i].replace(word[j],'')
  y1[i]=y1[i].strip()            //removes the leading & trailing whitespaces 
  if y1[i]!='':
    output.append(y1[i])         // adds into the 'output' list

print(output)

enter image description here

代码:

temp = ""
for y1_sentence in y1:
    y1_word = y1_sentence.split(" ")

    for i in y1_word:
        if i not in word:
            temp = temp + " " + i
    output.append(temp)
    temp = ""

real_output = []

for output_string in output:
    temp1 = output_string.strip()
    real_output.append(temp1)

Code

Output

早上好

python中有一个函数叫做str.replace(old, new[, max])。在

old表示要替换的旧子字符串。在

new代表新的子字符串,它将替换旧的子字符串。在

max是可选的,在您的案例中不需要。在

还必须指出的是,字符串在python中是不可变的。这意味着您必须将返回值replace()分配给您使用的变量。在

for x in y1:
    for w in word:
        x = x.replace(w, "")

这应该可以很好地工作,但是我确信有一种更聪明的方法可以用Python来实现。看看这里的例子:https://www.tutorialspoint.com/python/string_replace.htm

相关问题 更多 >