In Python, strings can be represented using either single quotes (‘ ‘) or double quotes (” “). In this tutorial, we will learn how to create string with single quotes in Python. We’ll walk through each example, along with the code and its output.
Create a String with Single Quotes in Python
Let us see different examples of how to create a string with single quotes in Python.
1- Create a Simple String with Single Quotes in Python
To create a simple string using single quotes in Python, just enclose the text between single quotes like the below example.
Example
city = 'New York'
print(city)
Output:
New York
2- Create a String with Single Quote Inside a String
If you need to include single quotes within your string, you can use double quotes to enclose the string in Python.
Example:
city = "St. John's"
print(city)
Output:
St. John's
3- Create a String with Escaping Single Quotes with Backslashes in Python
Alternatively, you can escape the single quote character within a single-quoted string by using a backslash () before the single quote in Python.
Example:
city = 'St. John\'s'
print(city)
Output:
St. John's
4- Create a string in Python by Mixing Single and Double Quotes
Sometimes, in Python, you may need to include both single and double quotes in your string. In such cases, you can use the backslash to escape either the single or double quotes.
Example:
quote = 'Andrea said, "It\'s time to visit San Francisco."'
print(quote)
Output:
Andrea said, "It's time to visit San Francisco."
5- Using Triple Quotes to Create Multi-Line Strings
f you want to create a multi-line string with single quotes in Python, you can use triple single quotes (”’ ”’).
Example:
multiline_string = '''This is a list of cities in the United States:
- New York
- Los Angeles
- Chicago
- Houston
- Phoenix
- Philadelphia'''
print(multiline_string)
Output:
This is a list of cities in the United States:
- New York
- Los Angeles
- Chicago
- Houston
- Phoenix
- Philadelphia
Conclusion
In this Python basic programming tutorial, we learned various ways to create and work with strings using single quotes in Python. Remember to use backslashes to escape single quotes when needed or enclose your strings with different types of quotes to avoid conflicts.
You may also like:
- How to Create a String from a List in Python
- Create a String with Variables in Python
- Create a String with Newline in Python
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.