繁体   English   中英

在不使用.translate、.replace 或 strip() 的情况下从字符串中删除 '\n'

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM