Python: os.join.path() [duplicate] - python

This question already has answers here:
Why do backslashes appear twice?
(2 answers)
Closed 6 years ago.
I used os.join.path() to load image in a folder. But I found the function cannot give accurate path when it is used in defining another function in some cases. For example:
def Myfuncion(something)
desiredPath = os.path.join('myPath','apple.jpeg')
#desiredPath = os.path.normpath(os.path.join('myPath','apple.jpeg'))
print desiredPath
return
When I implement the function, the printed result of the path is:
myPath\apple.jpeg
It is illegal for image loading. But os.path.join() works well in Pythonconsole.
How to make the path generated in such function definition have double backslashes?
Also, it is noted os.path.normpath also cannot work well sometimes. For example:
os.path.normpath('myPath\apple')
It should give the result:
myPath\\apple
But instead, it results in:
'myPath\x07pple'
How come??

\a is equivalent to \x07. (See escape sequence part in String and bytes literals.)
>>> '\a'
'\x07'
You need to escape \ to mean backslash literally:
>>> '\\a'
'\\a'
>>> print('\\a')
\a
or, use raw string literal:
>>> r'\a'
'\\a'
>>> print(r'\a')
\a

Related

How to satisfy "[FLAKE8 W605] invalid escape sequence '\.'" and string format in the mean time? [duplicate]

This question already has answers here:
Combine f-string and raw string literal
(5 answers)
Closed 1 year ago.
I have an issue in python. My original regex expression is:
f"regex(metrics_api_failure\.prod\.[\w_]+\.{method_name}\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)"
(method_name is a local variable) and I got a lint warning:
"[FLAKE8 W605] invalid escape sequence '\.'Arc(W605)"
Which looks like recommends me to use r as the regex prefix. But if I do:
r"regex(metrics_api_failure\.prod\.[\w_]+\.{method_name}\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)"
The {method_name} becomes the string type rather than a passed in variable.
Does anyone have an idea how to solve this dilemma?
Pass in the expression:
r"regex(metrics_api_failure\.prod\.[\w_]+\." + method_name + r"\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)"
Essentially, use Python string concatenation to accomplish the same thing that you were doing with the brackets. Then, r"" type string escaping should work.
or use a raw format string:
rf"regex(metrics_api_failure\.prod\.[\w_]+\.{method_name}\.\d+\.\d+\.[\w_]+\.[\w_]+\.sum\.60)"

How to use repr() instead of backquotes in Python 3 [duplicate]

This question already has answers here:
Having both single and double quotation in a Python string
(9 answers)
Closed 3 years ago.
I'm looking for a way to declare a string that contains double quotes and single quote.
In javascript I would do
let str = `"," '`
But when I try the same syntax in python, my IDE shows this error
Python version 3.7 does not support backquotes, use repr() instead
How can I use repr() to achieve this result?
The reason the error message says what it does is because backquotes have never been used in Python to do what you want. Instead, they used to be a shortcut for using the repr function, that is no longer supported.
According to documentation it take an object
Everything is an object in Python, so there is no issue there. But there is an issue in that the repr function does not do what you want.
We need to go back to the original question instead:
I'm looking for a way to declare a string that contains double quotes and single quote.
In Python, you may either escape whichever quote is the one you used for the string, for example:
"\",\" '" # using double quotes
'"," \'' # using single quotes
Or you may use so-called triple quotes:
""""," '""" # like so
But beware that this does not work if you have the same kind of quote at the end of the string:
# '''"," '''' -- does not work!
'''"," \'''' # works, but it defeats the purpose
In each case, '"," \'' is the form that Python will use to report the string back to you.
The message in the IDE is referring to using backticks around a variable name or other expression. In Python 2, `someVar` was a shortcut for repr(someVar).
But this isn't really what you're trying to do. The message is simply hard-coded for any use of backticks.
You just have to escape the quotes that are the same as the string delimiter.
s = '"," \''
I figured that out
So literally all I had to do was this
text = repr(",'") # returns this string ",'"
The part that confused me was I wasn't sure how to pass the argument to the function since according to documentation I should have passed an object, not a string or a list of string. Until I realized that a string is an object too
A few examples that helped me to understand it in details
>>> print("123")
123
>>> print(repr("123"))
'123'
>>> print(repr(",'"))
",'"

How to write a string starting with ' and ending with " in Python? [duplicate]

This question already has answers here:
Having both single and double quotation in a Python string
(9 answers)
Closed 5 years ago.
I'd like to save the following characters 'bar" as a string variable, but it seems to be more complicated than I thought :
foo = 'bar" is not a valid string.
foo = ''bar"' is not a valid string either.
foo = '''bar"'' is still not valid.
foo = ''''bar"''' actually saves '\'bar"'
What is the proper syntax in this case?
The last string saves '\'bar"' as the representation, but it is the string you're looking for, just print it:
foo = ''''bar"'''
print(foo)
'bar"
when you hit enter in the interactive interpreter you'll get it's repr which escapes the second ' to create the string.
Using a triple quoted literal is the only way to define this without explicitly using escapes. You can get the same result by escaping quotes:
print('\'foo"')
'foo"
print("'foo\"")
'foo"

format() function in python - Usage of multiple curly brackets {{{}}} [duplicate]

This question already has answers here:
How do I escape curly-brace ({}) characters in a string while using .format (or an f-string)?
(23 answers)
Closed 6 years ago.
again :)
I found this bit of code
col_width=[13,11]
header=['First Name','Last Name']
format_specs = ["{{:{}}}".format(col_width[i]) for i in range(len(col_width))]
lheader=[format_specs[i].format(self.__header[i]) for i in range(nb_columns)]
How Python evaluate this statement? Why we use three { when we have one element to format in every iteration?
when you do {{}}, python skips the replacement of {} and makes it the part of string. Below is the sample example to explain this:
>>> '{{}}'.format(3) # with two '{{}}'
'{}' # nothing added to the string, instead made inner `{}` as the part of string
>>> '{{{}}}'.format(3) # with three '{{{}}}'
'{3}' # replaced third one with the number
Similarly, your expression is evaluating as:
>>> '{{:{}}}'.format(3)
'{:3}' # during creation of "format_specs"
For details, refer: Format String Syntax document.

Issues handling strings with .encode('string-escape') method

I am working with variables containing directory paths in python on a windows machine, and as such need to convert string litterals to raw strings (removing escape sequences). All is fine when i use the os.getcwd() function and convert using the method .encode('string-escape'), but as soon as i try doing the same with a hard coded string it wont work. This is especially confusing as both objects are of the same type (string), and as such should behave in exactly the same way.
My code is:
import os
dir1 = os.getcwd()
type1 = type(dir1)
print type1
print dir1.encode('string-escape')
print "\n\n"
dir2 = "C:\Users\StaM\Desktop\brba\test1"
type2 = type(dir2)
print type2
print dir2.encode('string-escape')
And my output is:
<type 'str'>
C:\\Users\\StaM\\Desktop\\brba\\test1
<type 'str'>
C:\\Users\\StaM\\Desktop\x08rba\test1
As you can see both objects are the same type yet the behaviour is different in handling escape sequences. Any ideas on why this is happening and how to get this to work properly? All explanations / suggestions / solutions would be highly appreciated, I really want to understand what is going on here. Thnx
Please note: This question is about the .encode() method and not 'r' flag... Using the 'r' flag for raw strings is not an option here, as i am passing the variables containing directory paths into my program to construct a larger string to represent DOS commands.
The reason for this behavior is that the os.getcwd() function returns a pre-formatted string inclusive of double "\" even when pre-fixed to an escape character. While the .encode() method will only append the second "\" if the character that follows it is not an escape character.
>>> import os
>>> dir = os.getcwd()
>>> print "%r" %dir
'C:\\Users\\StaM\\Desktop\\brba\\test1'
The solution here is to use a dictionary to define all possible escape characters, then use a loop to locate these characters in the string in question and to append a secondary "\" directly preceding any escape characters. This should be done prior to using the .encode() method.
BOOM!

Categories

Resources