Definition
📌 Strings
Python strings (str) are sequences of characters, and like lists, they support indexing and slicing.
Syntax
syntax
name = "text"
name[0] # first character
name[0:3] # slice
f"Hello, {name}!"Example
py
name = "CodeyHub"
print(f"Name: {name}")
print("Length:", len(name))
print("Upper:", name.upper())Output
outputName: CodeyHub
Length: 8
Upper: CODEYHUB
Important Points
- Strings are immutable — methods like
.upper()return a new string rather than modifying the original. - Use
len(string)to get the character count (not a method on the string itself). - Slicing
string[start:end]extracts a substring, excluding the end index. - f-strings (
f"{variable}") are the modern, preferred way to build formatted text.
Common Mistakes
- Trying to modify a string in place, like
name[0] = 'X'— Python strings don't support item assignment. - Forgetting that slicing's end index is excluded, similar to
range(). - Using older
%or.format()styles when a clearer f-string would do.
Interview Tip
🎯 Before your interview
Know Python string slicing well —
s[::-1] to reverse a string is a very common quick interview trick.
