python-3.x 如何删除购物清单中的某个元素,同时删除该元素的\n,以便将清单上移而不留下间隙

hjzp0vay  于 2023-02-14  发布在  Python
关注(0)|答案(1)|浏览(127)

我试图使一个购物清单,但每次我删除一个项目,它留下了一个很大的差距,看起来很尴尬,请有人能帮助,我仍然是非常新的这一切,我只学了一两个月,所以一个简单的答案将是非常感谢:

def subtract(user):
    x = 0
    while x == False:
        answer = input("What would you like to subtract?")
        if answer in user:
            user = user.replace(answer,"")
            y = 0
            print("your list is:" + user)
            add_or_subtract(user)
            x == True
            break
        else:
            print ("sorry, I do not recognise this, please try again.")

def add(user):
    x = 0
    while x == False:
        answer = input(str("what would you like to add?".lower()))
        if answer in user:
            print ("sorry, this is already in the list")
        else:
            user = user + "\n" + answer
            print ("Your list is: " + user)
        answer = input("are you finished adding?".lower())
        if answer in ("yes", "yea", "ye"):
            answer1 = input("do you want to subtract or finish?")
            if answer1 in ("subtract"):
                subtract(user)
                x == True
                break
            elif answer1 in ("finish"):
                print (user)
                x == True
                break
            else:
                print("Sorry I do not recognise this")

def add_or_subtract(user):
    x = 0
    while x == False:
        answer = input ("do you want to add or subtract or finish?".lower())
        if answer in ("add","addition"):
            add(user)
            x == True
            break
        elif answer in ("subtract","takeaway"):
            subtract (user)
            x == True
            break
        elif answer in ("complete", "finish"):
            print ("your final list is: " + user)
            x == True
            break
        else:
            print ("sorry i do not recognise this")
        
        
def initial(user):
    x = 0
    while x == False:
        user = input("please type out your first item:".lower())
        content = input(str("your first item is "+ user + " are you content with that?".lower()))
        if content in "no":
            user = ""
            continue
        elif content in "yes":
            add_or_subtract(user)
            x == True
            break
                        
                        
shopping = ""
initial(shopping)

还有,有没有更好的方法来做到这一点,我觉得有,我可以使用一个列表来记录所有的项目,有没有一种方法,我可以存储现有的列表到一个数据库,然后在更新时重用它?

7bsow1i6

7bsow1i61#

出现间隙的原因是您忘记了\n字符(换行符),因此在替换时,请在回答之前放置'\n'

def subtract(user):
    x = 0
    while x == False:
        answer = input("What would you like to subtract?")
        if answer in user:
            user = user.replace('\n'+answer,"") # where it is edited
            y = 0
            print("your list is:" + user)
            add_or_subtract(user)
            x == True
            break
        else:
            print ("sorry, I do not recognise this, please try again.")

相关问题