[英]Removing '\n' from a string without using .translate, .replace or strip()
我正在制作一個簡單的基於文本的游戲作為學習項目。 我正在嘗試添加一個功能,用戶可以輸入“保存”,他們的統計數據將被寫入一個名為“save.txt”的 txt 文件,以便在程序停止后,玩家可以上傳他們以前的統計數據和從他們離開的地方開始。
這是保存的代碼:
用戶輸入“保存”和 class 屬性作為文本保存到文本文件中,一次一行
elif first_step == 'save':
f = open("save.txt", "w")
f.write(f'''{player1.name}
{player1.char_type} #value is 'Wizard'
{player1.life}
{player1.energy}
{player1.strength}
{player1.money}
{player1.weapon_lvl}
{player1.wakefulness}
{player1.days_left}
{player1.battle_count}''')
f.close()
但是,我還需要用戶能夠在下次運行游戲時加載他們保存的統計數據。 所以他們會輸入“加載”,他們的統計數據將被更新。
我試圖一次讀取一行文本文件,然后該行的值將依次變為相關 class 屬性的值,一次一個。 如果我在不先將其轉換為字符串的情況下執行此操作,則會出現問題,例如某些行被跳過,因為 python 將 2 行作為一個讀取並將它們一起作為一個列表。
所以,我嘗試了以下方法:
在下面的示例中,我只顯示來自 class 屬性“player1.name”和“player1.char_type”的數據,如上所示,以免使這個問題盡可能短。
elif first_step == 'load':
f = open("save.txt", 'r')
player1.name_saved = f.readline() #reads the first line of the text file and assigns it's value to player1.name_saved
player1.name_saved2 = str(player1.name_saved) # converts the value of player1.name_saved to a string and saves that string in player1.name_saved2
player1.name = player1.name_saved2 #assigns the value of player1.name_saved to the class attribute player1.name
player1.char_type_saved = f.readlines(1) #reads the second line of the txt file and saves it in player1.char_type_saved
player1.char_type_saved2 = str(player1.char_type_saved) #converts the value of player1.char_type_saved into a string and assigns that value to player1.char_type_saved2
此時,我會將 player1.char_type_saved2 的值分配給 class 屬性 player1.char_type 以便玩家1.char_type 的值使玩家能夠加載上次玩游戲時的前一個角色類型。 這應該使 player1.char_type = 'Wizard' 的值,但我得到 '['Wizard\n']'
我嘗試了以下方法來刪除括號和 \n:
final_player1.char_type = player1.char_type_saved2.translate({ord(c): None for c in "[']\n" }) #this is intended to remove everything from the string except for Wizard
出於某種原因,上面只刪除了方括號和標點符號,但沒有從末尾刪除 \n。
然后我嘗試了以下方法來刪除\n:
final_player1.char_type = final_player1.char_type.replace("\n", "")
final_player1.char_type 仍然是“向導\n”
我也嘗試過使用 strip() 但我沒有成功。
如果有人可以幫助我,我將不勝感激。 抱歉,如果我把這個問題復雜化了,但是如果沒有大量信息就很難說清楚。 讓我知道這是否太多或是否需要更多信息來回答。
如果'\n'
總是在最后,最好使用:
s = 'wizard\n'
s = s[:-1]
print(s, s)
Output:
wizard wizard
但我仍然認為strip()
是最好的:
s = 'wizard\n'
s = s.strip()
print(s, s)
Output:
wizard wizard
Normaly 它應該只適用於
char_type = "Wizard\n"
char_type.replace("\n", "")
print(char_type)
output 將是“向導”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.