What is a String?
A string in Python is a sequence of characters enclosed in single quotes (‘ ‘), double quotes (” “), or triple quotes (”’ ”’ or “”” “””).
Strings are used to store text such as names, messages, or any combination of letters, numbers, and symbols.
Example:
name = "Harry Potter"
house = 'Gryffindor'
quote = """I solemnly swear that I am up to no good."""
String Indexing & Slicing
-
Indexing → Accessing individual characters by their position (index starts from 0).
-
Slicing → Extracting a part of the string using
[start:end].
Example:
text = "Python"
print(text[0]) # P (first character)
print(text[-1]) # n (last character)
print(text[0:4]) # Pyth (slice from index 0 to 3)
String Concatenation (Joining)
We can join (concatenate) two strings using the + operator.
first = "Hello"
second = "World"
result = first + " " + second
print(result) # Hello World
String Methods (Common Ones)
Python provides many built-in methods for working with strings.
text = " python is FUN "
print(text.upper()) # PYTHON IS FUN
print(text.lower()) # python is fun
print(text.strip()) # removes spaces → "python is FUN"
print(text.replace("FUN", "awesome")) # python is awesome
print(len(text)) # 16 (length of string including spaces)
Key Takeaways:
-
Strings store text data in Python.
-
Indexing helps access single characters, and slicing extracts parts.
-
Concatenation joins strings.
-
String methods allow formatting, modifying, and analyzing text.
