简体   繁体   中英

How I can get newline represented by string "" from .txt file (not talking about \n) in python

If I'll create tab in notepad and then copy that to python code in string "" it works.

How can I get enter, newline as string? I don't want \\n that will be represented as newline in print statement I want newline that will be understood by python if I'll get it from the .txt file. Example

my_file = open("output.txt", "r") print(my_file.read()) my_file.close()

If you will copy question you will see what I mean. Output text is like this:

1 `` 2

`` is enter

When I copy each character into new variable output I get is like this when I write text back

1 2

I want to store in some way newline in variable when I get it from text file.

Well, the idea of using the '\\n' representation for newline character is because it is a control character.

There are about 30 control characters in ASCII table and they are used to instruct devices ('\\n' for new line, '\\t' for tabulator, '\\a' for beep, etc.), rather than represent some printable information. That means that they are in the file, they even have their own number in ASCII table like letters and numbers, but you can't see them in the file.

So if you need to put them somewhere, you usually use the '\\n' representation. Don't worry, Python knows that and will place newline into the string instead of '\\n', so I would recommend you to use '\\n'. There is another way to put a newline into a Python string. You can append a character from ASCII table to string by its number.

Example:

mystring = ""
mystring += "First line"
mystring += chr(10)     //number of newline in ASCII is 10
mystring += "Second line"

It really is no different to any other programming language. \\n is understood as a newline if you get it from a file opened in text mode.

It is not tied to the print statement, so

enter = '\n' 

is valid. The characters \\n are translated to the newline for your platform by python.

If you open in binary mode then you might need something else, on Windows typically \\r\\n .

However to answer your question, you can use a triple quoted string:

>>> x = """
... """

But, that is just a newline!

>>> x
'\n'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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