Strings in Python
A string is a sequence of characters enclosed in single quotes, double quotes, or triple quotes. Strings are immutable — once created, individual characters cannot be changed. Python treats strings as sequences, so all sequence operations (indexing, slicing, iteration) apply to them.
---
Creating Strings
```
s1 = 'Hello'
s2 = "World"
s3 = """This is
a multiline string."""
```
---
Indexing and Slicing
Characters are accessed by index (0-based). Negative indexing counts from the end.
Indexing
```
s = "Python"
print(s[0]) # P
print(s[-1]) # n
```
Slicing — s[start:stop:step]
```
s = "Computer"
print(s[0:4]) # Comp
print(s[::2]) # Cmue
print(s[::-1]) # retupmoc (reverse)
```
---
String Operations
- Concatenation (+): joins two strings — "Hello" + " " + "World" = "Hello World"
- Repetition ( · ): repeats a string — "ab" · 3 = "ababab"
- Membership (in / not in): "Py" in "Python" gives True
---
Built-in String Functions and Methods
Common methods
```
s = "hello world"
print(len(s)) # 11
print(s.upper()) # HELLO WORLD
print(s.capitalize()) # Hello world
print(s.title()) # Hello World
print(s.replace("world", "Python")) # hello Python
```
Searching and splitting
```
s = "apple,banana,cherry"
print(s.find("banana")) # 6 (index of first occurrence)
print(s.count("a")) # 4
parts = s.split(",") # ['apple', 'banana', 'cherry']
print(",".join(parts)) # apple,banana,cherry
```
---
Checking String Properties
Python provides predicate methods that return True or False:
| Method | Returns True if... |
|--------|-------------------|
| isalpha() | all characters are alphabetic |
| isdigit() | all characters are digits |
| isalnum() | all alphabetic or digit |
| isspace() | all whitespace |
| isupper() | all uppercase |
| islower() | all lowercase |
Predicate methods
```
print("abc".isalpha()) # True
print("123".isdigit()) # True
print("Ab3".isalnum()) # True
```
---
String Formatting
Using format()
```
name = "Riya"
score = 95
print("Student {} scored {}".format(name, score))
# Output: Student Riya scored 95
```
---
Traversing a String
Iterating character by character
```
vowels = 0
for ch in "Education":
if ch in "aeiouAEIOU":
vowels += 1
print("Vowels:", vowels) # Vowels: 5
```
---
Common mistakes
- Immutability confusion — trying s[0] = 'A' raises a TypeError; create a new string instead.
- Index out of range — accessing an index beyond len(s)-1 raises IndexError.
- Slice step of 0 — s[::0] raises ValueError; step cannot be zero.
- find() vs index() — find() returns -1 if not found; index() raises ValueError.
---
Summary
Strings are immutable sequences of characters. They support indexing, slicing, concatenation, and repetition. A rich set of built-in methods (upper, lower, find, split, join, replace, etc.) makes string processing powerful and concise.