I had a similar problem and stumbled upon this question, and know thanks to Nick Olson-Harris' answer that the solution lies with changing the string.
Two ways of solving it:
Get the path you want using native python functions, e.g.:
test = os.getcwd() # In case the path in question is your current directory print(repr(test))This makes it platform independent and it now works with
.encode. If this is an option for you, it's the more elegant solution.If your string is not a path, define it in a way compatible with python strings, in this case by escaping your backslashes:
test = 'C:\\Windows\\Users\\alexb\\' print(repr(test))
In general, to make a raw string out of a string variable, I use this:
string = "C:\\Windows\Users\alexb"
raw_string = r"{}".format(string)
output:
'C:\\\\Windows\\Users\\alexb'
Regex Search raw string on variable?
how to turn a string argument into raw string
python - How do I put a variable’s value inside a string (interpolate it into the string)? - Stack Overflow
How to turn a BeautifulSoup object into a String?
I need to perform a regex search that includes a variable that may contain regex characters in it. I'd like to have the re.search interpret the variable as a raw string but can't seem to find the proper format.
Example:
my_variable = "[id-1\s][" searchRegex = re.search(my_variable+[^&\n\s]*", current_line)
Since I can't quote out my_variable, how can I ensure re.search interprets it as a raw string?
UPDATE: I ended up using re.escape() to solve the problem per u/zahlman
my_variable = "[id-1\s][" searchRegex = re.search(re.escape(my_variable)+[^&\n\s]*", current_line)
Hi I am working on my project which involves retrieving image and folder paths so I can display them.
I saw that when putting in paths you need to replace \ with \\ due to python syntax
so I wrote this function to try and do that
#returns a string replacing the \ with double \\ To operate on
def slashreturn(string):
string2 = r'{}'.format(string)
ustring = string2.replace("\\","/")
print(ustring)
post = ""
for i in ustring:
if i == "/":
post += str(i*2)
else:
post += i
return print(post.replace("/","\\"))I quickly came up against the (SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape) Error. Researching this I found that turning the input into raw string would solve the issue and it does however I need the process to be automated. Thats why I tried doing the
string2 = r'{}'.format(string)But still no luck. I still get the error.
I would really appreciate if anyone could help me out with how to do this
cheers!
Using f-strings:
plot.savefig(f'hanning{num}.pdf')
This was added in 3.6 and is the new preferred way.
Using str.format():
plot.savefig('hanning{0}.pdf'.format(num))
String concatenation:
plot.savefig('hanning' + str(num) + '.pdf')
Conversion Specifier:
plot.savefig('hanning%s.pdf' % num)
Using local variable names (neat trick):
plot.savefig('hanning%(num)s.pdf' % locals())
Using string.Template:
plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))
See also:
- Fancier Output Formatting - The Python Tutorial
- Python 3's f-Strings: An Improved String Formatting Syntax (Guide) - RealPython
With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to write this with a briefer syntax:
>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
With the example given in the question, it would look like this
plot.savefig(f'hanning{num}.pdf')