having spacing issues in using "\n" in a separate file - python

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).

Related

Why does python add additional backslashes to the path?

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.

Hwo to write newline without escape sequence

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.

removing weird double quotes (from excel file) in python string

I'm loading in an excel file to python3 using xlrd. They are basically lines of text in a spreadsheet. On some of these lines are quotation marks. For example, one line can be:
She said, "My name is Jennifer."
When I'm reading them into python and making them into strings, the double quotes are read in as a weird double quote character that looks like a double quote in italics. I'm assuming that somewhere along the way, python read in the character as some foreign character rather than actual double quotes due to some encoding issue or something. So in the above example, if I assign that line as "text", then we'll have something like the following (although not exactly since I don't actually type out the line, so imagine "text" was already assigned beforehand):
text = 'She said, “My name is Jennifer.”'
text[10] == '"'
The second line will spit out a False because it doesn't seem to recognize it as a normal double quote character. I'm working within the Mac terminal if that makes a difference.
My questions are:
1. Is there a way to easily strip these weird double quotes?
2. Is there a way when I read in the file to get python to recognize them as double quotes properly?
I'm assuming that somewhere along the way, python read in the character as some foreign character
Yes; it read that in because that's what the file data actually represents.
rather than actual double quotes due to some encoding issue or something.
There's no issue with the encoding. The actual character is not an "actual double quote".
Is there a way to easily strip these weird double quotes?
You can use the .replace method of strings as you would normally, to either replace them with an "actual double quote" or with nothing.
Is there a way when I read in the file to get python to recognize them as double quotes properly?
If you're looking for them, you can compare them to the character they actually are.
As noted in the comment, they are most likely U+201C LEFT DOUBLE QUOTATION MARK and U+201D RIGHT DOUBLE QUOTATION MARK. They're used so that opening and closing quotes can look different (by curving in different directions), which pretty typography normally does (as opposed to using " which is simply more convenient for programmers). You represent them in Python with a Unicode escape, thus:
text[10] == '\u201c'
You could also have directly asked Python for this info, by asking for text[10] at the Python command line (which would evaluate that and show you the representation), or explicitly in a script with e.g. print(repr(text[10])).

Format string confusing

Hi im new to Python and Ive been trying to get format print to work but, and this may be me being new, but it seems to be very badly implemented.Any examples for 2.7.6 dont work for the new version and their aren't any real examples I could find on the internet for 3.3. As such I would like to ask for a good example of how format string works. For instance ive been trying to get this to work from my homework.
day,date,year,hour,and minutes must be separate variables.
using one formatted print statement,print the following:
Date:5/31/2013
Time: 3:45 pm
I can get it to work with this code:
def date():
Month=5
Day=31
Year=2013
Hours=3
Minutes=45
Scale='pm'
a="Date: %i/%i/%i\nTime: %i:%i %s" %(Month,Day,Year,Hours,Minutes,Scale)
print(a)
It works but its not one line as asked for. Please help format is so confusing.
The \n in your format string is inserting the new line character. Remove the \n, and you will not have the newline any longer.
Characters preceded by a backslash are known as escape characters. They can be used to insert special formatting into strings. For example:
\n is the newline character,
\t is the tab character
Remove \n because that is used to create a line break.

How to append '\\?\' to the front of a file path in Python

I'm trying to work with some long file paths (Windows) in Python and have come across some problems. After reading the question here, it looks as though I need to append '\\?\' to the front of my long file paths in order to use them with os.stat(filepath). The problem I'm having is that I can't create a string in Python that ends in a backslash. The question here points out that you can't even end strings in Python with a single '\' character.
Is there anything in any of the Python standard libraries or anywhere else that lets you simply append '\\?\' to the front of a file path you already have? Or is there any other work around for working with long file paths in Windows with Python? It seems like such a simple thing to do, but I can't figure it out for the life of me.
"\\\\?\\" should give you exactly the string you want.
Longer answer: of course you can end a string in Python with a backslash. You just can't do so when it's a "raw" string (one prefixed with an 'r'). Which you usually use for strings that contains (lots of) backslashes (to avoid the infamous "leaning toothpick" syndrome ;-))
Even with a raw string, you can end in a backslash with:
>>> print r'\\?\D:\Blah' + '\\'
\\?\D:\Blah\
or even:
>>> print r'\\?\D:\Blah' '\\'
\\?\D:\Blah\
since Python concatenates to literal strings into one.

Categories

Resources