In this tutorial, you'll learn to declare a string variable in python in 4 different ways.
1. Using Single Quotes
In the below example, it will simply declare a string using the single quotes and will print on the screen.
a_string = 'Hello World!' print(a_string)
Output
Hello World!
2. Using Double Quotes
You can also declare a string using double quotes in Python. The following is an example:
a_string = "Hello World!" print(a_string)
Output
Hello World!
3. Handle Single Quote in a String
Suppose you have an apostrophe (') in the string, then you would not be able to declare a string variable with single quotes. Apply these two methods to handle a single quote in a string:
a. Using Backslash (\) to Escape the Single Quote
a_string = 'Python is the world\'s best programming language.' print(a_string)
Output
Python is the world's best programming language.
b. Using Double Quotes
a_string = "Python is the world's best programming language." print(a_string)
Output
Python is the world's best programming language.
But what if a string is having both single and double quotes? The following is the way to handle it.
4. Handle Both Single and Double Quotes in a String in Python
a. Using Backslash (\)
Declare a variable with double quotes and put the backslash before double-quoted value.
a_string = "Python is the world's best \"programming language\"." print(a_string)
Output
Python is the world's best "programming language".
b. Using Three Double Quotes
Declare the string in three double quotes then no need to put a backslash to escape the quotes.
a_string = """Python is the world's best "programming language".""" print(a_string)
Output
Python is the world's best "programming language".
See also:
- Get Dates of Working Days Between Two Dates in Python (Exclude Weekends)
- How to Sort List of Dictionaries in Python By Key
- Python Logging Example