1. What is a String in Python? (Definition)
A string is an immutable sequence of Unicode characters used to represent text. For example, "hello" is a string containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
2. How to Declare Strings in Python?
In Python, you can declare both single-line and multi-line string.
✅ Single-Line Strings
You can declare single-line strings using:
- Single quotes
'...'
- Double quotes
"..."
Both work the same way.
Use double quotes if your string contains a single quote:
quote = "It's a beautiful day"
Use single quotes if your string contains double quotes:
dialogue = '"Python" is easy to learn'
✅ Multi-Line Strings
For multiple lines, use:
- Triple single quotes
'''...'''
- Triple double quotes
"""..."""
msg1 = '''This is a
multi-line string using
single quotes.'''
msg2 = """This is also a
multi-line string using
double quotes."""
Use triple double quotes ("""..."""
) for docstrings as recommended by Python’s PEP 257 style guide—they’re more commonly used and better supported by tools. Both work the same technically, but """..."""
is preferred for readability and consistency.
3. Types of Strings in Python:
In Python, strings can be represented in several ways depending on the use case. Understanding these types is essential for writing clean, efficient, and bug-free code.
✅ 1. Normal Strings
Standard string with escape sequences interpreted.
s = "Hello\nWorld"
print(s) # Output: Hello (newline) World
🟢 Use when you want escape characters like \n
, \t
, etc., to be interpreted.
✅ 2. Raw Strings
Escape sequences are not interpreted. Prefix with r
or R
.
path = r"C:\Users\New_Folder"
print(path) # Output: C:\Users\New_Folder
🟢 Use when dealing with:
- Regex patterns
- File paths on Windows
- Literal backslashes
✅ 3. f-Strings (Formatted String Literals)
Added in Python 3.6+. Supports inline expression evaluation.
name = "Rocky"
print(f"Hello, {name}") # Output: Hello, Rocky
🟢 Use when you want cleaner and faster string interpolation.
✅ 4. Byte Strings
Prefix with b
to create a bytes object (not Unicode).
data = b"Hello"
print(type(data)) # <class 'bytes'>
🟢 Use when dealing with:
- Binary files
- Network data
- Encoding/decoding
4. Python Escape Characters (with Examples):
Escape characters are used to insert characters that are illegal in a string.
Escape | Description | Example | Output |
---|---|---|---|
\n |
New Line | "Hello\nWorld" |
Hello World |
\t |
Horizontal Tab | "Hello\tWorld" |
Hello World |
\\ |
Backslash | "C:\\path" |
C:\path |
\" |
Double Quote | "She said, \"Hi!\"" |
She said, "Hi!" |
\' |
Single Quote | 'It\'s fine' |
It's fine |
\a |
Bell/Alert (system beep) | print("\a") |
Beep sound (may vary by OS) |
\b |
Backspace | "abc\b" |
ab |
\f |
Form feed | "Hello\fWorld" |
HelloWorld |
\r |
Carriage Return | "Hello\rWorld" |
World |
\v |
Vertical Tab | "Hello\vWorld" |
HelloWorld |
Tip: Use raw strings if you want to avoid interpreting escape characters, especially in regular expressions and file paths.
5. Various Operations on Strings in Python:
Python supports a rich set of operations on strings. Below are the major categories with explanations and code examples.
1. Concatenation
Joining two or more strings using the +
operator.
first = "Hello"
last = "World"
full = first + " " + last
print(full) # Output: Hello World
2. Repetition
Repeating a string multiple times using the *
operator.
line = "-=" * 10
print(line) # Output: -=-=-=-=-=-=-=-=-=-=-
3. Indexing
Access individual characters by index (starting from 0
).
s = "Python"
print(s[0]) # Output: P
print(s[-1]) # Output: n (last character)
4. Slicing
Extract a part (substring) using [start:stop:step]
.
s = "Python"
print(s[1:4]) # Output: yth
print(s[:3]) # Output: Pyt
print(s[::2]) # Output: Pto (every 2nd char)
print(s[::-1]) # Output: nohtyP (reversed)
5. Membership Testing
Check if a character or substring is present.
print("y" in "Python") # True
print("thon" not in "Python") # False
6. Length of String
Use len()
to get number of characters.
s = "Python"
print(len(s)) # Output: 6
7. Min / Max Character
Find smallest or largest character based on Unicode.
s = "abcXYZ"
print(min(s)) # Output: 'X'
print(max(s)) # Output: 'c'
8. Comparison
Strings can be compared using ==
, !=
, <
, >
, etc.
print("apple" < "banana") # True (lexicographical)
print("abc" == "ABC") # False (case-sensitive)
9. Iteration (Looping through characters)
for char in "Python":
print(char)
10. ASCII and Unicode Operations
print(ord('A')) # 65
print(chr(65)) # 'A'
11. Escape Sequences
Escape special characters like newline \n
, tab \t
, etc.
print("Line1\nLine2") # Output: Line1 (newline) Line2
12. Immutability of Strings
Strings are immutable — they cannot be changed in-place.
s = "Hello"
# s[0] = 'Y' # ❌ This will raise an error
s = "Yellow" # ✅ You can reassign a new value
13. String to List and Vice Versa
s = "Python"
lst = list(s) # ['P', 'y', 't', 'h', 'o', 'n']
new_s = "".join(lst) # 'Python'
14. String Formatting
name = "Rocky"
age = 25
print(f"My name is {name}, I am {age}")
15. Identity vs Equality
a = "hello"
b = "hello"
print(a == b) # True (values are equal)
print(a is b) # True (interned string, same object)
6. Python String Methods:
Python provides many built-in methods to work with strings. These methods do not modify the original string (because strings are immutable) — they return new strings.
1. str.upper()
Converts all characters to uppercase.
s = "python"
print(s.upper()) # Output: PYTHON
2. str.lower()
Converts all characters to lowercase.
s = "PYTHON"
print(s.lower()) # Output: python
3. str.title()
Converts the first character of each word to uppercase.
s = "python string methods"
print(s.title()) # Output: Python String Methods
4. str.capitalize()
Capitalizes the first character of the string.
s = "hello world"
print(s.capitalize()) # Output: Hello world
5. str.swapcase()
Swaps the case of each character.
s = "PyThOn"
print(s.swapcase()) # Output: pYtHoN
6. str.strip()
, lstrip()
, rstrip()
Removes whitespace (or custom characters) from ends.
s = " hello "
print(s.strip()) # 'hello'
print(s.lstrip()) # 'hello '
print(s.rstrip()) # ' hello'
7. str.replace(old, new, count)
Replaces occurrences of a substring.
s = "apple banana apple"
print(s.replace("apple", "orange")) # orange banana orange
8. str.find(sub)
, str.rfind(sub)
Finds the first/last index of a substring (returns -1 if not found).
s = "banana"
print(s.find("na")) # 2
print(s.rfind("na")) # 4
9. str.index(sub)
, str.rindex(sub)
Same as find()
but raises ValueError if not found.
s = "banana"
print(s.index("na")) # 2
10. str.count(sub)
Counts the number of times a substring appears.
s = "banana"
print(s.count("na")) # 2
11. str.startswith(prefix)
, str.endswith(suffix)
Checks if the string starts/ends with given prefix/suffix.
s = "hello world"
print(s.startswith("hello")) # True
print(s.endswith("world")) # True
12. str.split(sep=None)
Splits the string into a list.
s = "a,b,c"
print(s.split(",")) # ['a', 'b', 'c']
13. str.join(iterable)
Joins elements of an iterable with the string as separator.
words = ["join", "these", "words"]
print(" ".join(words)) # join these words
14. str.zfill(width)
Pads the string on the left with zeros to fill the width.
s = "42"
print(s.zfill(5)) # 00042
15. str.isdigit()
, isalpha()
, isalnum()
, etc.
Checks properties of strings.
print("123".isdigit()) # True
print("abc".isalpha()) # True
print("abc123".isalnum()) # True
print(" ".isspace()) # True
16. str.casefold()
Aggressive lowercase for case-insensitive comparisons.
print("Straße".casefold() == "strasse") # True
17. str.partition(sep)
Splits into 3 parts: before, separator, after.
s = "key=value"
print(s.partition("=")) # ('key', '=', 'value')
18. str.center(width, fillchar=' ')
Centers string in given width with optional fill character.
s = "hello"
print(s.center(11, "-")) # ---hello---
Top comments (0)