String
A string in Python is an immutable sequence of characters. Strings can be created with single quotes '...' or double quotes "...".
Strings are the most frequently used data type after numbers. User names, email addresses, chat messages, article paragraphs — they are all strings. Python treats strings as immutable sequences of characters, meaning that once a string is created, its content cannot be changed directly. Operations like replacing a character actually create a new string, rather than modifying the old one.
Python's strength lies in the ease of string manipulation. Slicing (s[0:5]) for cutting, various methods such as split() and join() for separating and joining, and f-strings for clean, expressive formatting. F-strings (Python 3.6+) are very popular because you can insert variables directly into a string with curly braces {}.
Common String Operations:
- Slicing:
s[0:5],s[::-1] - Methods: upper(), lower(), strip(), split(), join(), replace(), find()
- Formatting: f-string, format(), % formatting
Code Example
s = "Hello, Python!"
# Access & Slicing
print(s[0]) # H
print(s[0:5]) # Hello
print(s[::-1]) # !nohtyP ,olleH (reversed)
# String methods
print(s.upper()) # HELLO, PYTHON!
print(s.lower()) # hello, python!
print(s.split(", ")) # ['Hello', 'Python!']
print(s.replace("Hello", "Hi"))
# f-string (Python 3.6+)
name = "John"
age = 25
print(f"{name} is {age} years old")
Code Explanation
The string s = "Hello, Python!" contains 14 characters (including spaces and punctuation). Indices in Python start from 0, so s[0] takes the letter 'H'. Slicing s[0:5] takes characters from index 0 up to 4 (index 5 is not included), producing "Hello". The s[::-1] trick reverses the string completely.
The upper() and lower() methods change capitalization. split(", ") cuts the string by a delimiter (comma-space) into a list: ['Hello', 'Python!']. replace("Hello", "Hi") replaces a word.
Finally, the f-string inserts the variables name and age directly into the text. This is cleaner than concatenating strings with the + operator.
Everyday Example
Validating an email address on a registration form. The program checks whether the input contains an @ character and a dot, then normalizes it with lower().
email = " [email protected] "
email = email.strip().lower()
if "@" in email and "." in email:
print(f"Valid email: {email}")
else:
print("Email is not valid")
Summary
Strings are the foundation of communication in a Python program. With slicing, built-in methods, and f-strings, we can process text quickly and expressively. Good string manipulation skills are a must for every programmer.