Introduction
Strings are sequences of characters used to store text data.
String Operations
text = "Hello, Python!"
# Indexing and slicing
print(text[0]) # H
print(text[0:5]) # Hello
print(text[-6:]) # Python!
# String methods
print(text.upper()) # HELLO, PYTHON!
print(text.lower()) # hello, python!
print(text.replace("Python", "World"))
print(text.split(",")) # ['Hello', ' Python!']
String Formatting
name = "Alice"
age = 30
# f-strings (Python 3.6+)
print(f"My name is {name} and I'm {age}")
# format method
print("My name is {} and I'm {}".format(name, age))
# old style
print("My name is %s and I'm %d" % (name, age))
Practice Problems
- Count vowels and consonants in a string
- Check if string is palindrome
- Remove duplicates from string
- Find all occurrences of a substring
- Encrypt string using Caesar cipher