【问题标题】:'\r' added to end of everything input in python'\r' 添加到 python 中所有输入的末尾
【发布时间】:2014-11-06 22:24:42
【问题描述】:

我是该网站和编程的新手,所以如果我的问题最终很明显很容易回答,我提前道歉。我正在使用 notepad++ 和 python 3.2。

所以我的问题是,为什么在运行和测试我的程序时,我在 python 控制台中所做的每个输入的末尾都添加了一个 '\r' 和/或一个 '\n'?几天来我一直在互联网上寻找答案,我最接近问题的原因是python可能将返回键识别为要添加到字符串输入的字符。我发现这可能是我在所谓的“文本模式”下编码。

我尝试以不同的格式对程序进行编码,但没有成功。我的下一个想法是在另一台机器上尝试它,它可以正常工作,输入变量中的字符串不包含“\r”或“\n”。在此之后,我决定卸载并重新安装 python 和 notepad++(以及任何剩余文件)以查看问题是否存在。但同样,它没有任何区别。

这是我的代码。它是一个基本的聊天程序,可以读取、写入和保存到一个 csv 文件,直到最近我开始遇到这个问题(在另一个程序上工作时)。

def get_info():
    #get name and a starting message from the user
    name = input("what is your name? >")
    note = input("what say you? >")
    output = ">" + name + ">" + note + "\n"
    return(output)

def save_file(the_message):
    #this function appends the new message to the group list
    #needs argument to write (the_message is the argument)
    #returns nothing
    hard_drive = open("C:\\Users\Harry\Documents\Homework\A Levels\Computing\chat.csv", "r")
    hard_drive.write(the_message)
    hard_drive.close()

def read_file():
    message_file = open("C:\\Users\Harry\Documents\Homework\A Levels\Computing\chat.csv", "r")
    #"r" means read
    printable = message_file.read()
    message_file.close()
    return(printable)

while True:
    #calls get_info function in
    print_message = get_info()
    save_file(print_message)
    #saves return value of get_info
    messages = read_file()
    #calls in read_file and creates variable in which return value is copied
    print(messages)
    #return value of read_file is printed 

它似乎只出现在一个函数中,并且在我制作的所有其他程序(正在运行)中都是相同的。这是我在运行程序后调用该函数时在控制台中得到的内容:

>>>getinfo()
what is your name? >random
what say you? >anything
'>random\r>anything\r\n'

(函数的返回是底线 - 想发布图片但我是新用户) 我怀疑这是我的操作系统(Windows 8)的问题 - 有人有什么想法吗?

编辑:当我注意到问题时我正在处理的程序:

print("Address Book v2.6.9 \n")
print("This program will allow the user the add and search for users addresses \n")

def read_file():
    file_handle = open("C:\\Users\Harry\Documents\Homework\A Levels\Computing\Python\dataoct_24_2014.csv")
    #file is opened and read from, reference held in variable
    read = file_handle.read().splitlines()
    #variable 'read' holds reference to method which returns all lines from file as list of lists
    all_addresses = []
    for address in read:
        split_fields = address.split("|")
        all_addresses.append(split_fields)
        #this should make it easier when reading a writing by making a list
    #returns a list of lists containing strings, all separated by commas
    file_handle.close
    return all_addresses

def index():
    #this will determine the index number for new people added to the address book
    #read_file()
    contact_index = (len(read_file()))
    #assigns no. contacts the reference to number of lines in file
    return contact_index

def get_add_info(first, last, number):
    contact_index = index()
    #could make a function that assigns each new address with it's correct index
    formated_info = str(contact_index) + "|" + first + "|" + last + "|" + str(number)
    #remember to add \n to end when writing to file
    return formated_info        

#def search_file(user_input)

#def append_to_file(add_person):

while True:
    user_option = input("Type 'search' to search for a contact or 'add' to add a new contact to your address book: ")
    #other options will be created later
    if user_option == "search":
        print("(this will work later)")
    elif user_option == "add":
        print("Please enter new contact details: \n")
        first_name_input = input("Enter first name of person: ")
        last_name_input = input("Enter last tame of person: ")
        phone_number_input = input("Enter phone number of person: ")
        get_add_info(first_name_input, last_name_input, phone_number_input)
    else:
        print("Have you spelt you choice correctly?")

【问题讨论】:

  • Windows 通常以 \r\n 结束行,Python 应该将 \r\n 更改为 \n,它不包含在 input() 返回的字符串中。我不知道你是如何改变工作的。 >>> input("x: ') 有同样的问题吗?您是否尝试过在同一台机器上以其他用户身份运行 Python?
  • 感谢您的快速回复,是的,我仍然遇到这个问题。我还没有尝试在其他用户上运行它 - 我现在就试试
  • #我在我的guest账号上做了一个测试程序如下: variable_1 = input("input: ") def get_info(): variable_2 = input("input: ") return variable_2 #返回这个函数似乎是我唯一一次遇到这个问题

标签: python-3.x notepad++


【解决方案1】:

在 Python 中,“the (backslash) character encodes difficult-to-type characters into a string”。处理反斜杠字符编码称为转义

print() 函数使用转义return() 函数不使用转义,它输出原始字符串

例如:

>>>string = "hello\n"
>>>def test(input):
       return(input)
>>>test(string)
'hello\n'
>>>print(string)
hello

你的主脚本没有出现这个问题的原因:

  • messages 包含来自 get_info 的原始字符串
  • 您在messages 上使用了print() 函数

由于您在messages 上使用了print() 函数,因此messages 将使用转义 显示。

为什么你首先拥有它们:

  • 您在get_info() 的字符串中明确添加了"\n"
  • Python 使用不同的行结束约定,具体取决于您的 操作系统,写入文件时

基于 Mac OS 的计算机遵循"CR"(carriage return aka '\r') convention。这意味着写入 csv 文件的字符串将包含 "\r" 行结尾。

现在为什么get_info() 专门显示/插入行尾,我不确定;我需要您提供更多信息,但这听起来像是您的 Notepad++ 设置的问题。

您可以使用编写函数来删除多余的转义字符。例如,您可以使用rstrip()

【讨论】:

  • 感谢所有信息 - 帮助我更多地了解 python(我会投票,但我没有足够的代表)。这对我来说是个问题的原因是它确实会影响我在其他程序中的其余脚本。例如,在另一个程序的“if”语句中,如果输入变量包含某个单词,则执行后面的代码。现在因为它包含 '\r' 代码不能被执行但它不等于它应该的文本。
  • 我测试过的另一台机器正在运行 Windows 7 和相同版本的 python,并且没有这个问题。如果它有帮助,我可以从我正在处理的当前程序中发布代码,这是我第一次注意到问题的地方。我认为这就是它的起源。
  • 很高兴知道,我会为你做更多的研究。也发布当前程序中的代码,这将很有帮助。当您在 python ide 中定义和运行 get_info () 函数时是否会出现此问题,或者仅在使用 notepad++ 时会出现此问题?同时尝试创建一个函数来删除多余的字符。
  • 谢谢,我会将我正在制作的地址簿(当前程序)的代码添加到问题的末尾 - 它未完成,它只是 read_file() 函数和 While True 语句我目前正在努力。
  • 我在 IDLE 中运行了相同的函数,但它没有在每个输入的末尾加上 '\r',这意味着问题一定出在 notepad++ 或 python shell。
猜你喜欢
  • 1970-01-01
  • 2019-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
相关资源
最近更新 更多