A string in Python is a sequence of characters.
Strings are immutable, meaning once created, their content cannot be changed.
They can be created using single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """).
string1 = 'Hello, Python!'
string2 = "Hello, World!"
string3 = '''This is a
multi-line string'''s = "Hello"
s[0] = 'h' # ❌ TypeError: 'str' object does not support item assignmentNote: To "change" a string you must create a new one:
s = "Hello"
s = "h" + s[1:] # 'hello's = "Python"
print(s[0]) # Output: 'P'
print(s[-1]) # Output: 'n'Accessing an index that doesn't exist raises IndexError:
# print(s[100]) # IndexError: string index out of ranges = "Hello123!@#"Strings can contain letters, digits, punctuation, whitespace and special characters.
s = "Python"
for char in s:
print(char)
# Output: P y t h o n (each on a new line)s = "Python"
print(len(s)) # Output: 6s = "python"
print(s.upper()) # 'PYTHON'
print(s.lower()) # 'python's = "hello python world"
print(s.capitalize()) # 'Hello python world'
print(s.title()) # 'Hello Python World's = " Hello, World! "
print(s.strip()) # 'Hello, World!'
print(s.lstrip()) # 'Hello, World! '
print(s.rstrip()) # ' Hello, World!'s = "Hello, World!"
print(s.replace("World", "Python")) # 'Hello, Python!'s = "apple,orange,banana"
print(s.split(",")) # ['apple', 'orange', 'banana']fruits = ['apple', 'orange', 'banana']
print(", ".join(fruits)) # 'apple, orange, banana's = "Hello, Python!"
print(s.find("Python")) # 7
print(s.find("Java")) # -1s = "banana"
print(s.count("a")) # 3s = "Hello, World!"
print(s.startswith("Hello")) # True
print(s.endswith("World!")) # Trueprint("Python".isalpha()) # True
print("12345".isdigit()) # True
print("123456".isnumeric()) # Trueprint("hello".islower()) # True
print("HELLO".isupper()) # Truename = "John"; age = 25
print("My name is {} and I am {} years old.".format(name, age))
print(f"My name is {name} and I am {age} years old.")print("Hello World".swapcase()) # 'hELLO wORLD'Syntax: string[start:stop:step]
s = "Hello, Python!"
print(s[0:5]) # 'Hello'
print(s[7:]) # 'Python!'
print(s[::-1]) # '!nohtyP ,olleH'| Escape | Meaning |
|---|---|
\n |
Newline |
\t |
Tab |
\\ |
Backslash |
\' |
Single quote |
\" |
Double quote |
print("Hello\nPython")
print("He said, \"Python is fun!\"")Converting between str (text) and bytes requires encoding/decoding:
s = "café"
b = s.encode("utf-8") # bytes
print(b) # b'caf\xc3\xa9'
print(b.decode("utf-8")) # 'café'Mistakes in encoding/decoding can raise UnicodeEncodeError or UnicodeDecodeError.
-
TypeError: 'str' object does not support item assignment- Cause: Trying to change a character via index (
s[0] = 'h') — strings are immutable. - Fix: Build a new string (
s = 'h' + s[1:]).
- Cause: Trying to change a character via index (
-
IndexError: string index out of range- Cause: Accessing
s[i]whereiis outside0 .. len(s)-1. - Fix: Check
len(s)or use slicing which is safe (e.g.,s[0:100]).
- Cause: Accessing
-
AttributeError: 'NoneType' object has no attribute 'upper'- Cause: Calling a string method on a variable that is
None(e.g.,s = None; s.upper()). - Fix: Ensure the variable is a string before calling methods (
if s is not None:).
- Cause: Calling a string method on a variable that is
-
TypeError: can only concatenate str (not "int") to str- Cause: Trying to
+astrand a non-str (e.g.,"Age: " + 25). - Fix: Convert with
str(25)or use f-strings:f"Age: {25}".
- Cause: Trying to
-
ValueErrorwhen converting strings to numbers- Example:
int("abc")raisesValueError. - Fix: Validate or handle with
try/except.
- Example:
-
UnicodeEncodeError/UnicodeDecodeError- Cause: Wrong encoding during
.encode()or.decode()or when writing/reading files. - Fix: Use the correct encoding (e.g.,
"utf-8") consistently.
- Cause: Wrong encoding during
-
Unexpected results due to invisible characters
- Cause: Strings may contain whitespace, non-printable characters, or different newline conventions.
- Fix: Use
.strip()/repr()/ord()to inspect and clean strings.
Repeated string concatenation in large loops can be inefficient (strings are immutable). For heavy concatenation, prefer:
- Building a list and
''.join(list_of_parts) - Using
io.StringIOfor very large dynamic building
Example (inefficient):
s = ""
for i in range(10000):
s += str(i) # creates many intermediate stringsEfficient alternative:
parts = []
for i in range(10000):
parts.append(str(i))
s = "".join(parts)-
Index & slicing
- Given
s = "PythonRocks", print:- First character
- Last character
- Substring
"thonR" - Reversed string
- Given
-
Immutable update
- Convert
"Hello"to"hELLO"using slicing and concatenation.
- Convert
-
Parsing
- Given
"name:age:city" = "Alice:30:Paris", split into variables and print an f-string:Alice is 30 and lives in Paris.
- Given
-
Validation
- Write a function
is_valid_username(s)that returnsTrueifs:- is 3–16 characters long,
- contains only letters and digits,
- starts with a letter.
- Write a function
-
Counting
- Count vowels in a string (both uppercase & lowercase) and print counts for each vowel.
-
Safe conversion
- Write a function
to_int(s)that tries to convertstointand returnsNoneif conversion fails (handle exceptions).
- Write a function
-
Encoding
- Read a Unicode string with accents (e.g.,
"café") and show its UTF-8 byte representation and back.
- Read a Unicode string with accents (e.g.,
-
Performance
- Create a list of 10,000 small strings and join them into one string. Measure (optionally) the difference between repeated
+=vs list +join.
- Create a list of 10,000 small strings and join them into one string. Measure (optionally) the difference between repeated
- Strings are immutable, ordered, and iterable.
- Use slicing, built-in methods (
split,join,replace, etc.) for manipulation and parsing. - Watch for common errors:
TypeError(mutation/concatenation),IndexError,AttributeError,ValueError, and Unicode errors. - For heavy concatenation, build parts and use
join().