簡體   English   中英

Python:如何允許用戶選擇要編輯的行?

[英]Python: How to allow user to select line to edit?

我一直在嘗試將文本文件加載到Python中並替換最后一個單詞。 文本文件如下所示:

A1 I'm at the shop with Bill
B3 I'm going to the shop with Sarah
E3 I was at the shop with nobody
F5 I'm at the shop with Cameron

我想允許用戶選擇要編輯的行。 因此,他們可以在第二行輸入B3,然后在末尾替換名稱。 我已經嘗試過使用它作為函數進行很多事情,但是我無法對要編輯的行進行編號。

使用ord(c)函數將字母轉換為數字,然后使用該字母選擇行索引。

choice = input("Enter the row you would like to change")

if choice.isalpha(): # if they enter 1 or b or C
    choice_num = ord(choice.lower()) - 97
else:
    choice_num = choice

with open('shops.txt') as shoplist:
    lines = shoplist.read().splitlines()
    name = lines[choice_num].split()[-1]
    lines[choice_num] = lines[2].replace(name, "Steve")
    with open ('shops.txt','w') as shoplist:
        for l in lines:
            shoplist.write(l+"\n')

暫無
暫無

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

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