Multiple checks but still SyntaxError: EOL while scanning string literal - python-3.x

I have checked on this string multiple times to ensure that the (".") are in place, but the message
File "<ipython-input-13-ef09f7b4583b>", line 48 plt.savefig("C:\scratch\\data\"+str(angle).zfill(3)+".")
SyntaxError: EOL while scanning string literal
still comes up.
Any suggestions?
if save is not False:
plt.savefig("C:\scratch\\data\"+str(angle).zfill(3)+".png")
plt.close("all")
else:
plt.show()
return

A Python string can not terminate with \ as this will escape the closing " (or ').
You have several options:
Use double-back slashes in a constant manner:
plt.savefig("C:\\scratch\\data\\" + str(angle).zfill(3) + ".png")
Use .format, preferably with combination of raw string to avoid problems in case a directory name starts with t, n or any other character that will become a control sequence when prefixed with \:
plt.savefig(r"C:\scratch\data\{}.png".format(str(angle).zfill(3)))

Related

EOL error while concatinating strings when backslash(\) is used in python

Why doesn't it work? my gut feeling is it has something to do with the slashes(\);
savepath = ("C:\\Python\" + date4filename + ".txt")
Error is
File "C:\python\temp.py", line 2
savepath=("C:\\Python\" + date4filename)
^
SyntaxError: EOL while scanning string literal
[Finished in 0.191s]
Back slash has special meaning which is used to take away special meaning of special characters when prefixed, here it is double quote ("). For this reason we have raw strings in python.
Raw strings are defined using r' ' . When raw strings are used all characters inside string are treated normal with no special meaning
Since backslash has special meaning, to use actual backslash we need to use (\\)
savepath = ("C:\\Python\\" + date4filename + ".txt")
Not to make it complex, use os.path library
import os.path
os.path.join("c://python/", date4filename, ".txt")
To avoid these path problems, you can absolutely use *nix style forwardslash(/) in python regardless of platform

How do I add the ' symbol to a string

I had someone help with a prior question to turn hexadecimal to string, but I want the string to output surrounded with '
so it returns 'I0KB' instead of just I0KB.
What I have:
with open('D:\new 4.txt', 'w') as f:
f.write('if not (GetItemTypeId(GetSoldItem())==$49304B42) then\n')
def hex_match_to_string(m):
return ''.join([chr(int(m.group(1)[i:i+2], 16)) for i in range(0, len(m.group(1)), 2)])
# ...
line = re.sub(r'\$((?:\w\w\w\w\w\w\w\w)+)', hex_match_to_string, line)
file_out.write(line)
output:
if not (GetItemTypeId(GetSoldItem())==I0KB) then
but I want it to output
if not (GetItemTypeId(GetSoldItem())=='I0KB') then
and using
def hex_match_to_string(m):
return ''.join(',[chr(int(m.group(1)[i:i+2], 16)) for i in range(0, len(m.group(1)), 2)],')
...gives me a syntax error even though I read that join(a,b,c) is the way to combine strings.
Thanks in advance for the help, and sorry I am clueless for what should be an easy task.
You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string.
You should not add the quotes to the argument passed to join, but wrap the result of the join with quotes:
return "'" + ''.join([chr(int(m.group(1)[i:i+2], 16)) for i in range(0, len(m.group(1)), 2)]) + "'"
I think it's important to distinguish between enclosing a string between, single, double, or triple quotation marks. See answers here regarding the most common use of the third (the so-called doc-strings).
While most of the time you can use " and ' interchangeably, you can use them together in order to escape the quotation:
>>> print("''")
''
>>> print('"')
"
You can also use the double quotes three times to escape any double quotes in between:
>>> print(""" " " "j""")
" " "j
But I'd suggest against the last option, because it doesn't always work as expected, for example, print(""""""") will throw an error. (And of course, you could always use the \ to escape any special character.)

\n in Python 3 confusion

I am pretty new at python. So, I get this
SyntaxError: unexpected character after line continuation character
after running this:
print (full_name.title()\nfull_name.upper()\nfull_name.lower())
Any idea why?
You must separate each string by a comma, and the use quotes around the strings:
print(full_name.title(), '\n', full_name.upper(), '\n', full_name.lower())
Alternatively, you could first concatenate the fragments, then print the resulting string:
string_to_print = full_name.title() + '\n' + full_name.upper() + '\n' + full_name.lower()
print(string_to_print)
There are more sophisticated approaches too (f-strings, format, __str__, etc.) that you may want to look up once you have mastered the basics.

I think I'm adding the path to an image folder incorrectly in the logic of my discord.py bot

I am trying to get the bot to respond with a randomly selected image from a folder on my pc:
if message.content == "look at this":
imgList = os.listdir("C:\Users\Alien\Desktop\BOTS\TAL\IMAGES")
imgString = random.choice(imgList)
path = "C:\Users\Alien\Desktop\BOTS\TAL\IMAGES" + imgString
await client.send_file(message.channel, path)
This is part of a longer .py file with a lot of different code that all works fine with the necessary intros/outros etc
It ran fine before I added this but now when I try to run it prints:
C:\Users\Alien\PycharmProjects\tal-1.0\venv\Scripts\python.exe C:/Users/Alien/PycharmProjects/tal-1.0/tal-1.0.py
File "C:/Users/Alien/PycharmProjects/tal-1.0/tal-1.0.py", line 27
imgList = os.listdir("C:\Users\Alien\Desktop\BOTS\TAL\IMAGES")
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
Process finished with exit code 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
This is telling you there an escape character error, in position 2-3, which are characters \U
\ is an escape character for strings. It allows you to include things like a single-quote inside a single quote string: var = 'you\'re' will keep the single quote without closing the string.
You're using the escape character \ in your string(, which you're doing because it is part of your filesystem path). So it's trying to decode the next character, U, which it doesn't know how to do since it doesn't need to be escaped.
Instead you need to escape the escape character. You'll need to write \\ in each place that you have \.
Your solution needs something like this in all your paths:
imgList = os.listdir("C:\\Users\\Alien\\Desktop\\BOTS\\TAL\\IMAGES")

Syntax error in removing bad character in groovy

Hello I have a string like a= " $ 2 187.00" . I tried removing all the white spaces and the bad characters like a.replaceAll("\\s","").replace("$","") . but i am getting error
Impossible to parse JSON response: SyntaxError: JSON.parse: bad escaped character how to remove the bad character in this expression so that the value becomes 2187.00.Kindly help me .Thanks in advance
def a = ' $ 2 187.00'
a.replaceAll(/\s/,"").replaceAll(/\$/,"")
// or simply
a.replaceAll(/[\s\$]/,"")
It should return 2187.00.
Note
that $ has special meaning in double quoted strings literals "" , called as GString.
In groovy, you can user regex literal, using that is better than using regex with multiple escape sequences in string.

Resources