How to fix SyntaxError: unterminated string literal (detected at line in python, in this scenario, I forgot by mistakenly closing quotes ( ” ) with f string different code lines, especially 1st line and last line code that is why we face this error in python. This is one of the command errors in python, If face this type of error just find where you miss the opening and closing parentheses “(“ “)” just enter then our code error free see the below code.
Table of Contents
Wrong Code: unterminated string literal python
# Just create age input variable
a = input("What is Your Current age?\n")
Y = 101 - int(a)
M = Y * 12
W = M * 4
D = W * 7
print(f"You have {D} Days {W} Weeks, {M} Months And {Y} Years Left In Your Life)
print("Hello World")
Error Massage
File "/home/kali/python/webproject/error/main.py", line 8
print(f"You have {D} Days {W} Weeks, {M} Months And {Y} Years Left In Your Life)
^
SyntaxError: unterminated string literal (detected at line 8)
Wrong code line
Missing closing quotes ( ” ).
print(f"You have {D} Days {W} Weeks, {M} Months And {Y} Years Left In Your Life)
Correct code line
print(f"You have {D} Days {W} Weeks, {M} Months And {Y} Years Left In Your Life")
print(” “).
Entire Correct Code line
# Just create age input variable
a = input("What is Your Current age?\n")
Y = 101 - int(a)
M = Y * 12
W = M * 4
D = W * 7
print(f"You have {D} Days {W} Weeks, {M} Months And {Y} Years Left In Your Life")
print("Hello World")
What is unterminated string literal Python?
Syntax in python sets forth a specific symbol for coding elements like opening and closing quotes (“ “ ), Whenever we miss the closing quotes with f string that time we face SyntaxError: unterminated string literal In Python. See the above example.
How to Fix unterminated string literal Python?
Syntax in python sets forth a specific symbol for coding elements like opening and closing quotes (), Whenever we miss the closing quotes with f string that time we face SyntaxError: unterminated string literal so we need to find in which line of code we miss special closing quotes ( “ )symbol and need to enter correct symbols, See the above example.
For more information visit Amol Blog Code YouTube Channel.
Решил запустить скрипт сделал все по инструкции и тут выскакивает такое. Не подскажите как это исправить друзья программисты буду очень благодарен(
Ошибка
C:\Users\Наталья\AppData\Local\Programs\Python\Python311\python.exe C:\Users\Наталья\PycharmProjects\pythonProject1\main.py
File "C:\Users\Наталья\PycharmProjects\pythonProject1\main.py", line 35
unq_filter_params =["colorbalance=rs=.3","colorbalance=gs=-
^
SyntaxError: unterminated string literal (detected at line 35)
Process finished with exit code 1
Сам код
import moviepy
from moviepy.editor import *
import random
from pathlib import Path
import string
def create_file_list(folder):
return [str(f) for f in Path(folder).iterdir()]
def create_image_list(folder):
image_list=[]
folder = Path(folder)
if folder.is_file():
image = ImageClip(str(folder),duration=1)
image_list.append(image)
if folder.is_dir():
for file in sorted(folder.iterdir(), reverse=True):
image = ImageClip(str(file),duration=1)
image_list.append(image)
return image_list
def filename(folder):
file_name = ''.join(random.choice(string.ascii_lowercase)
for i in range(5))
file_name = str(Path(folder).joinpath(file_name + '.mp4'))
return file_name
#Папка для сохранения видео
result_folder = r'C:\Users\Наталья\Desktop\SAVE'
#Папка с картиками
images = create_image_list(r'C:\Users\Наталья\Desktop\PNG')
#Папка с видео которые будут обработаны
video_ls = create_file_list(r'C:\Users\Наталья\Desktop\VIDEO')
#Фильтрыpip
unq_filter_params =["colorbalance=rs=.3","colorbalance=gs=-
0.20","colorbalance=gs=0.20","colorbalance=bs=-
0.30","colorbalance=bs=0.30","colorbalance=rm=0.30","colorbalanc
e=rm=-0.30","colorbalance=gm=-0.25","colorbalance=bm=-
0.25","colorbalance=rh=-0.15","colorbalance=gh=-
0.20","colorbalance=bh=-0.20"]
Скриншот фрагмента кода удален модератором.
We can’t deny that errors are inevitable, and one of them is the syntaxerror: unterminated string literal.
Whether you’re new to coding or even a pro developer, it’s important to understand this error so you can troubleshoot it and bug-free programs.
If you are struggling to fix this error, this article is indeed for you.
In this article, we will explore how to fix the unterminated string literal, a SyntaxError in Python and JavaScript.
The syntaxerror: unterminated string literal occurs when there is an unterminated string literal somewhere in your code. String literals should be enclosed by single (‘) or double (“) quotes.
Here’s an example of code that would cause a SyntaxError, specifically an unterminated string literal, in both Python and JavaScript
Python:
sample_string = "Hi, welcome to Itsourcecode, this a sample of an unterminated string
JavaScript:
let sampleString = "Hi, welcome to Itsourcecode, this a sample of an unterminated string;
As you have noticed in both examples, the string is not properly enclosed by quotes. The closing quote is missing, as a result, it will throw a SyntaxError.
Why does “unterminated string literal” SyntaxError occur?
The syntaxerror: unterminated string literal occurs when you forget to put a closing quotation mark at the end of a string in Python or JavaScript.
It can also happen when you have escaped your string literal incorrectly or if your string literal is split across multiple lines.
Here are the common causes of why this error keeps on bothering you:
👉 One common reason for this error is when the opening and closing quotation marks do not match.
👉 Forgetting to close the string with the correct quotation mark on any line can also trigger this error.
👉 Having special characters within a string, like unescaped quotation marks or newline characters, can interfere with properly ending a string literal.
How to fix the “syntaxerror: unterminated string literal”?
To fix the syntaxerror: unterminated string literal, check if you have to open and close quotes for your string literal, ensure that you have properly escaped your string literal correctly, and avoid splitting your string literal across multiple lines.
Here are the following solutions that can help you to resolve the error.
Solution 1: Add the missing quotation mark
Adding the missing quotation mark fixes the error right away.
For example in Python:
sample_string = "Hi, welcome to Itsourcecode, this a sample of an unterminated string" ✅
print(sample_string)
Output:
Hi, welcome to Itsourcecode, this a sample of an unterminated string
For example in JavaScript:
let sampleString = "Hi, welcome to Itsourcecode, this a sample of an unterminated string";✅
console.log(sampleString);
Output:
Hi, welcome to Itsourcecode, this a sample of an unterminated string
Solution 2: Split the string across multiple lines using the + operator
If you want to split a string across multiple lines, you can use the + operator to concatenate multiple strings.
For example in Python:
sample_string = ("Hi " ✅
"welcome to Itsourcecode"
" this a sample of an unterminated string")
print(sample_string)
Output:
Hi welcome to Itsourcecode this a sample of an unterminated string
For example in JavaScript:
let sampleString = ("Hi, " ✅
+"welcome to Itsourcecode "
+ "this a sample of an unterminated string");
console.log(sampleString);
Output:
Hi, welcome to Itsourcecode this a sample of an unterminated string
Solution 3: Use backslashcharacter or escape quotes within the string
If you want to include a quote character within a string, you need to escape it using a backslash (\).
For example in Python:
sample_string = ("Hi welcome to \"Itsourcecode\" this a sample of an unterminated string")✅
print(sample_string)
Output:
Hi welcome to "Itsourcecode" this a sample of an unterminated string
For example in JavaScript:
let sampleString = ("Hi welcome to \"Itsourcecode\" this a sample of an unterminated string")✅
console.log(sampleString);
Output:
Hi welcome to "Itsourcecode" this a sample of an unterminated string
Solution 4: Use the correct type of quotes
Ensure that you are using the correct type of quotes for your string literals. If you start a string with a single quote (‘), you need to end it with a single quote.
If you start a string with a double quote (“), you need to end it with a double quote.
For example in Python:
sample_string = ('Hi welcome to "Itsourcecode" this a sample of an unterminated string')✅
print(sample_string)
For example in JavaScript:
let sampleString = ('Hi welcome to "Itsourcecode" this a sample of an unterminated string')✅
console.log(sampleString);
Solution 5: Split the string across multiple lines using template literals (JavaScript only)
You can use template literals in JavaScript to split a string across multiple lines.
For example:
let sampleString = `Hi ✅
welcome to Itsourcecode
this a sample of an unterminated string`;
console.log(sampleString);
Output:
Hi
welcome to Itsourcecode
this a sample of an unterminated string
Conclusion
In conclusion, the error message syntaxerror: unterminated string literal occurs when there is an unterminated string literal somewhere in your code. String literals should be enclosed by single (‘) or double (“) quotes.
To fix this error, you have to check if you have to open and close quotes for your string literal, ensure that you have properly escaped your string literal correctly, and avoid splitting your string literal across multiple lines.
This article already discussed what this error is all about and multiple ways to resolve this error.
By executing the solutions above, you can master this SyntaxError with the help of this guide.
You could also check out other SyntaxError articles that may help you in the future if you encounter them.
- Syntaxerror unexpected reserved word await
- Uncaught syntaxerror expected expression got
- Syntaxerror await is only valid in async function
We are hoping that this article helps you fix the error. Thank you for reading itsourcecoders 😊
I am trying to use a shutil script I found but it receives SyntaxError: unterminated string literal (detected at line 4)
. Any assistance would be appreciated to fixing this or new script
import shutil
import os
source = r"C:\Users\[username]\Downloads\"
dest1 = r" C:\Users\[username]\Desktop\Reports\14"
dest2 = r" C:\Users\[username]\Desktop\Reports\52"
dest3 = r" C:\Users\[username]\Desktop\Reports\59"
files = os.listdir(source)
for f in files:
if (f.startswith("Log 14")):
shutil.move(f, dest1)
elif (f.startswith("Log 54")):
shutil.move(f, dest2)
asked Dec 9, 2021 at 20:42
Ric Ric
311 gold badge1 silver badge3 bronze badges
8
Watch out for smart quotes ”
. They need to be double quotes "
.
You had smart quotes instead of normal ones. Indenting is also not correct.
Here is the fixed code:
import shutil
import os
source = "C:\\Users\\[username]\\Downloads\\"
dest1 = "C:\\Users\\[username]\\Desktop\\Reports\\14"
dest2 = "C:\\Users\\[username]\\Desktop\\Reports\\52"
dest3 = "C:\\Users\\[username]\\Desktop\\Reports\\59"
files = os.listdir(source)
for f in files:
if f.startswith("Log 14"):
shutil.move(source + f, dest1)
elif f.startswith("Log 54"):
shutil.move(source + f, dest2)
wjandrea
28.5k9 gold badges62 silver badges82 bronze badges
answered Dec 9, 2021 at 21:48
norbotnorbot
1876 bronze badges
2
Smart Quotation Marks strike again.
Using BabelStone, one can determine the unicode identification of each character in your code.
The start/ending quotes you’re used to are \U0022
. However, the end of the URL on dest2
ends with a different character, which is \U201D
. This is a different character. Easiest way to fix this is to retype out the quotation marks in your IDE.
Input: "”
U+0022 : QUOTATION MARK {double quote}
U+201D : RIGHT DOUBLE QUOTATION MARK {double comma quotation mark}
answered Dec 9, 2021 at 21:43
blackbrandtblackbrandt
2,0101 gold badge15 silver badges32 bronze badges
import os
if os.name == 'nt': #check if windows
a='\\'
else:
a='/'
source = "C:"+a+"Users"+a+"[username]"+a+"Downloads"+a
answered Jul 7, 2022 at 8:21
RITESH RITESH
1331 silver badge5 bronze badges
3
Currently, you cannot nest quotes inside an f-string, even inside a replacement field. The "
in the first argument to replace
is terminating the f-string literal, meaning the "
that you want to terminate the string is actually starting a new string literal.
For now, use f"""..."""
to define the literal.
This restriction has been lifted as of (at least) Python
3.12.0.b1 , due to the formalization of f-string literals in the grammar by PEP 701:
Python 3.12.0b1 (main, Jun 4 2023, 16:00:02) [Clang 11.1.0 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> string = str
>>> value = 9
>>> f"'{string(value).replace('"', '""')}'"
"'9'"
Python 3.12 just recently entered beta; 3.12.0b2 is currently available. The final release is expected in October 2023.