I wonder how to write \n, not using \n. What is the 'raw' way to write a new line?
Instead of
print("Hello\nWorld")
Output
Hello
World
I want
print("HelloSOMEENCODINGWorld)
Output
Hello
World
Is there a way to use ASCII, Hex, ... within the string?
You can use multi-line strings.
print("""Hello
World""")
But \n is better
You can use bash ANSI Escape Sequences:
print('Line1 \033[1B\033[50000DLine2',)
# \033[1B Gets cursor to the line below
# \033[50000D Gets the cursor 50000 spaces to the left , 50000 is just a random big number
You can refer this for more info on Bash ANSI Escape Sequences
One of the options is print('Hello{}World'.format(chr(10))).
One way of doing this might be through os.linesep
import os
print('This is a line with a line break\nin the middle')
print(f'This is a line with a line break {os.linesep}in the middle')
But as stated here:
Note: when writing to files using the Python API, do not use the os.linesep. Just use \n; Python automatically translates that to the proper newline character for your platform.
Related
I have a text file with a path that goes like this:
r"\\user\data\t83\rf\Desktop\QA"
When I try to read this file a print a line it returns the following string, I'm unable to open the file from this location:
'r"\\\\user\\data\\t83\\rf\\Desktop\\QA"\n'
Seems you've got Python code in your text file, so either sanitize your file, so it only includes the actual path (not a Python string representation) or you can try to fiddle with string replace until you're satisfied, or just evaluate the Python string.
Note that using eval() opens Padora's box (it as unsafe as it gets), it's safer to use ast.literal_eval() instead.
import ast
file_content = 'r"\\\\user\\data\\t83\\rf\\Desktop\\QA"\n'
print(eval(file_content)) # do not use this, it's only shown for the sake of completeness
print(ast.literal_eval(file_content))
Output:
\\user\data\t83\rf\Desktop\QA
\\user\data\t83\rf\Desktop\QA
Personally, I'd prefer to sanitize the file, so it only contains \\user\data\t83\rf\Desktop\QA
\ will wait for another character to form one like \n (new line) or \t (tab) therefore a single backslash will merge with the next character. To solve this if the next character is \\ it will represent the single backslash.
e.write("y.write('\n+d')")
I was trying to write this line of code into a separate python program
y.write('\n'+d)
and when it wrote it, it went like this
str.write('
'+d)
but the '+d) was up one space above this text
any suggestions to keep it in the same line?
e.write("y.write('\\n'+d)")
(escape the backslash to make it a literal character), or:
e.write(r"y.write('\n'+d)")
(use a raw string to make backslashes not special).
I have following line in my code:
if "♠" in text:
do_something()
When working no some UTF-16 encoded text files.
It works but it looks kind of silly (to me). Is there any way to write something along the lines of "\code for this character here" instead so it works on text data opened with UTF-16 encoding ?
Also how do I go around using this in regex ? Say I want to match every line beginning with ♠ or ♥ symbol.
Thanks for help :)
If you want a symbolic name, you can use \N{unicode character name}:
'\N{BLACK SPADE SUIT}'
(Name as found on http://www.fileformat.info/info/unicode/char/2660/index.htm).
I am printing a string to the python shell on a mac os 10.7.3.
The string contains new line characters, \n\r, and tabs, \t.
I'm not 100% sure what new line characters are used on each platform, however i've tried every combination (\n, \n\r, \r) and the newline characters are printed on the shell:
'hello\n\r\tworld'
I don't know what i'm doing wrong, any help is appreciated.
Thanks
What look to you like newlines and carriage returns are actually two characters each -- a back slash plus a normal character.
Fix this by using your_string.decode('string_escape'):
>>> s = 'hello\\n\\r\\tworld' # or s = r'hello\n\r\tworld'
>>> print s
hello\n\r\tworld
>>> print repr(s)
'hello\\n\\r\\tworld'
>>> print s.decode('string_escape')
hello
world
The following code:
key = open("C:\Scripts\private.ppk",'rb').read()
reads the file and assigns its data to the var key.
For a reason, backslashes are multiplied in the process. How can I make sure they don't get multiplied?
You ... don't. They are escaped when they are read in so that they will process properly when they are written out / used. If you're declaring strings and don't want to double up the back slashes you can use raw strings r'c:\myfile.txt', but that doesn't really apply to the contents of a file you're reading in.
>>> s = r'c:\boot.ini'
>>> s
'c:\\boot.ini'
>>> repr(s)
"'c:\\\\boot.ini'"
>>> print s
c:\boot.ini
>>>
As you can see, the extra slashes are stored internally, but when you use the value in a print statement (write a file, test for values, etc.) they're evaluated properly.
You should read this great blog post on python and the backslash escape character.
And under some circumstances, if
Python prints information to the
console, you will see the two
backslashes rather than one. For
example, this is part of the
difference between the repr() function
and the str() function.
myFilename =
"c:\newproject\typenames.txt" print
repr(myFilename), str(myFilename)
produces
'c:\newproject\typenames.txt'
c:\newproject\typenames.txt
Backslashes are represented as escaped. You'll see two backslashes for each real one existing on the file, but that is normal behaviour.
The reason is that the backslash is used in order to create codes that represent characters that cannot be easily represented, such as new line '\n' or tab '\t'.
Are you trying to put single backslashes in a string? Strings with backslashes require and escape character, in this case "\". It will print to the screen with a single slash
In fact there is a solution - using eval, as long as the file content can be wrapped into quotes of some kind. Following worked for me (PATH contains some script that executes Matlab):
MATLAB_EXE = "C:\Program Files (x86)\MATLAB\R2012b\bin\matlab.exe"
content = open(PATH).read()
MATLAB_EXE in content # False
content = eval(f'r"""{content}"""')
MATLAB_EXE in content # True
This works by evaluating the content as python string literal, making double escapes transform into single ones. Raw string is used to prevent escapes forming special characters.