需要从字符串中删除单词并显示删除的单词+剩余的字符串,可能的元组?

2024-07-08 16:00:12 发布

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

我是一个初学者,所以请容忍我。我提出了一个涉及三明治名称的问题来练习我的字符串操作以及它们包含的内容,我在下面的sandwich.txt中包含了一个示例

我编写了一个简短的代码来删除某个字符串,在本例中它是bacon,我想返回值[*what_I_removed*, *what_is_left_in_the_sandwich*]

sandwich.txt包含:

BLTsandwich_bread_bacon_lettuce_tomato_bread
BREADsandwich_bread_bread_bread
HAMsandwich_bread_ham_bread

这是我的密码:

import os
sandwich= open(os.path.join(os.getcwd(), 'sandwich.txt'), 'r').readlines()

def NoBacon(sandwich):
    for x in range (0,len(sandwich)):
        if sandwich[x].rstrip('\n') in user_input:
            return [sandwich[x].rstrip('\n'),user_input.replace(sandwich[x].rstrip('\n')+'_','')]
            break

print (NoBacon(sandwich))

输出为:

['bacon', 'BLTsandwich_bread_lettuce_tomato_bread']

python有更简单的方法吗


Tags: 字符串intxtinputoswhatbaconuser
2条回答
sandwich= ["BLTsandwich_bread_bacon_lettuce_tomato_bread",
"BREADsandwich_bread_bread_bread",
"HAMsandwich_bread_ham_bread"]

to_replace = ["bacon"]

def NoBacon(sandwich):
    replacements_made = []
    for line in sandwich:
        for word in to_replace:
            words_replaced = []
            if word in line:
                words_replaced.append(word)
                line = line.replace(word, "")
        replacements_made.append((words_replaced, line))
    return replacements_made

print (NoBacon(sandwich))

结果是这样的

$ python mmmm_bacon.py 
[(['bacon'], 'BLTsandwich_bread__lettuce_tomato_bread'), ([], 'BREADsandwich_bread_bread_bread'), ([], 'HAMsandwich_bread_ham_bread')]

我将留给您来解决如何使用用户输入以及如何删除额外的_字符

我知道我迟到了,但这只是另一个选择

import os
#sandwich= open(os.path.join(os.getcwd(), 'sandwich.txt'), 'r').readlines()

sandwich = """
BLTsandwich_bread_bacon_lettuce_tomato_bread
BREADsandwich_bread_bread_bacon_bread_bacon
bacon_HAMsandwich_bacon_bread_ham_bread
Bacon_HAMsandwich_bacon_bread_ham_bread
"""

user_input = "bacon"

def NoBacon(sandwich):

    result = []
    length = len(user_input)
    lines = sandwich.strip().split('\n')

    for line in lines:
        cleaned_line = line.replace(user_input, '')
        if len(line) - len(cleaned_line) >= length:
            result.append([user_input, cleaned_line])


    return result

for k in (NoBacon(sandwich)):
    print k

上述输入字符串的输出示例:

['bacon', 'BLTsandwich_bread__lettuce_tomato_bread']
['bacon', 'BREADsandwich_bread_bread__bread_']
['bacon', '_HAMsandwich__bread_ham_bread

相关问题 更多 >

    热门问题