How to Create a String in Python: Simple Guide
In Python, you create a string by placing text inside
single quotes ('') or double quotes (""). You can also use triple quotes (''' ''' or """ """) for multi-line strings.Syntax
Strings in Python are sequences of characters enclosed in quotes. You can use single quotes, double quotes, or triple quotes for multi-line strings.
'text'- single quotes"text"- double quotes'''text'''or"""text"""- triple quotes for multi-line strings
python
single_quote_string = 'Hello' double_quote_string = "World" triple_quote_string = '''This is a multi-line string'''
Example
This example shows how to create strings using single, double, and triple quotes, and how to print them.
python
single = 'Hello' double = "World" multi_line = '''This is a multi-line string''' print(single) print(double) print(multi_line)
Output
Hello
World
This is a
multi-line
string
Common Pitfalls
Common mistakes include mixing quote types incorrectly or forgetting to close quotes, which causes errors. Also, using single quotes inside single-quoted strings without escaping will break the string.
Use different quote types or escape characters to fix these issues.
python
wrong_string = 'It\'s sunny' # This causes an error correct_string1 = "It's sunny" # Use double quotes outside correct_string2 = 'It\'s sunny' # Escape the single quote inside
Quick Reference
| Quote Type | Usage | Example |
|---|---|---|
| Single quotes | For simple strings | 'Hello' |
| Double quotes | For strings with single quotes inside | "It's sunny" |
| Triple quotes | For multi-line strings | '''Line 1 Line 2''' |
Key Takeaways
Create strings by enclosing text in single or double quotes.
Use triple quotes for multi-line strings.
Avoid mixing quotes incorrectly to prevent errors.
Escape quotes inside strings when needed.
Print strings to see their content in Python.