PCAP 31 03 PCAP Certified Associate Python Programmer · Free Practice Question Medium
Question 49
Q177 - Data Types
Which of the following are valid Python string literals?
(Select two answers.)
-
A
- 'All the king's horses'
-
B
- "\"
-
C
- "King's Cross Station"
-
D
- """The Knights Who Say 'Ni!'"""
Reveal correct answers
Correct answers: C, D
Explanation
Topics: string literals escape character single quotes double quotes
multi-line strings
Try it yourself:
- print("King's Cross Station") # King's Cross Station
- print("""The Knights Who Say 'Ni!'""") # The Knights Who Say 'Ni!'
- # print("\") # SyntaxError: EOL while scanning string literal
- # print('All the king's horses') # SyntaxError: invalid syntax
Explanation:
A single quote can be used in a string delimited by double quotes
(and vice versa).
And a single quote can be used in a multi-line string
delimited by triple double quotes (and vice versa).
Q177 (Please refer to this number, if you want to write me about this question.)
A. Single quotes ('') are used to define string literals in Python, and they can contain double quotes inside them without any issues. Therefore, 'All the king's horses' is not a valid Python string literal due to the unescaped single quote in "king's".
B. "\" is not a valid string literal in Python as it is an incomplete escape sequence. In Python, to include a backslash in a string, it needs to be escaped with another backslash like "\\".
C. Double quotes ("") are used to define string literals in Python, and they can contain single quotes inside them without any issues. Therefore, "King's Cross Station" is a valid Python string literal.
D. Triple quotes (""" """) are used to define multi-line string literals in Python, and they can contain single or double quotes without any escaping needed. Therefore, """The Knights Who Say 'Ni!'""" is a valid Python string literal.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
