
Python
Strings are the foundation of text processing. Let's understand what they are and how to create them in Python.
A string is a sequence of characters enclosed in quotes. Think of it as text wrapped for computer consumption. In Python, strings are immutableβonce created, they can't be changed.
# Three ways to create strings
single_quote = 'Hello'
double_quote = "World"
no_difference = 'Same as "double"'
print(single_quote) # Hello
print(double_quote) # WorldPython accepts single quotes (`'`), double quotes (`"`), and triple quotes (`'''` or `"""`). Use whichever is most convenient:
# Single and double quotes are equivalent
message1 = 'It\'s a beautiful day'
message2 = "It's a beautiful day"
# Triple quotes allow multi-line strings
poem = """
Roses are red,
Violets are blue,
Python is awesome,
And so are you!
"""
print(poem)Escape sequences are special character combinations starting with a backslash (`\`). They represent characters that can't be typed directly:
# Common escape sequences
newline_string = "Line 1\nLine 2" # \n = newline
tab_string = "Name\tAge" # \t = tab
quote_string = "He said \"Hi!\"" # \" = double quote
backslash_string = "C:\\Users\\Documents" # \\ = backslash
print(newline_string)
# Output:
# Line 1
# Line 2Raw strings (`r''` or `r""`) treat backslashes as literal characters, not escape sequences. Perfect for file paths and regular expressions:
# Without raw string (backslash interpreted)
normal = "C:\new\documents" # Problematic!
# With raw string (backslash literal)
raw = r"C:\new\documents" # Works perfectly
regex = r"\d+\.\d+" # Pattern for decimals
print(raw) # C:\new\documents
print(regex) # \d+\.\d+| Operation | Example | Result |
|---|---|---|
| Create string | `"Hello"` | `'Hello'` |
| Escape quote | `"It\'s"` | Error (use `"It's"` instead) |
| Newline | `"Line\nBreak"` | Multi-line output |
| Tab | `"Col1\tCol2"` | Spaced columns |
| Raw string | `r"C:\path"` | Literal backslashes |
| Concept | Remember |
|---|---|
| Quote choice | Single or double doesn't matter; pick one for consistency |
| Triple quotes | Use for multi-line strings or docstrings |
| Escape sequences | `\n`, `\t`, `\"`, `\\` are most common |
| Raw strings | Use `r""` for paths and regex patterns |
| Immutability | Strings can't be modified; create new ones instead |
Now that you understand string creation, learn how to access specific characters and portions of strings.
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep β’ Build Real β’ Verify Skills β’ Launch Forward