What are Strings?
In Python, strings are sequences of Unicode characters enclosed in single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """). They are immutable, meaning once created, their contents cannot be modified.
Strings are one of the most commonly used data types in Python and support various operations and methods for manipulation.
"Strings are immutable sequences of Unicode characters in Python."
Creating Strings
You can create strings using different types of quotes:
# Different ways to create strings
single_quote = 'Hello, World!'
double_quote = "Hello, World!"
triple_quote = '''This is a
multiline string'''
triple_double = """This is also a
multiline string"""
print(single_quote)
print(triple_quote)
String Indexing and Slicing
Strings support indexing and slicing operations:
# String indexing
text = "Python"
print(text[0]) # 'P' (first character)
print(text[1]) # 'y'
print(text[-1]) # 'n' (last character)
print(text[-2]) # 'o'
# String slicing
print(text[0:3]) # 'Pyt' (characters 0, 1, 2)
print(text[2:]) # 'thon' (from index 2 to end)
print(text[:4]) # 'Pyth' (from start to index 3)
print(text[::2]) # 'Pto' (every second character)
print(text[::-1]) # 'nohtyP' (reversed string)
String Concatenation and Repetition
You can combine and repeat strings:
# String concatenation
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # "John Doe"
# String repetition
laugh = "Ha" * 3
print(laugh) # "HaHaHa"
# Using join() for better performance
words = ["Hello", "World", "Python"]
sentence = " ".join(words)
print(sentence) # "Hello World Python"
String Methods
Python provides numerous built-in string methods:
Case Conversion Methods:
text = "Hello, World!"
print(text.upper()) # "HELLO, WORLD!"
print(text.lower()) # "hello, world!"
print(text.title()) # "Hello, World!"
print(text.capitalize()) # "Hello, world!"
print(text.swapcase()) # "hELLO, wORLD!"
Search and Replace Methods:
text = "Python is awesome"
print(text.find("is")) # 7 (index of "is")
print(text.index("is")) # 7 (same as find, but raises error if not found)
print(text.count("o")) # 2 (count occurrences of "o")
print(text.replace("awesome", "great")) # "Python is great"
Whitespace and Strip Methods:
text = " Hello, World! "
print(text.strip()) # "Hello, World!" (remove leading/trailing whitespace)
print(text.lstrip()) # "Hello, World! " (remove leading whitespace)
print(text.rstrip()) # " Hello, World!" (remove trailing whitespace)
Split and Join Methods:
text = "apple,banana,cherry"
# Split string into list
fruits = text.split(",")
print(fruits) # ['apple', 'banana', 'cherry']
# Join list into string
joined = "-".join(fruits)
print(joined) # "apple-banana-cherry"
Check Methods:
text = "Python123"
print(text.isalpha()) # False (contains numbers)
print(text.isdigit()) # False (contains letters)
print(text.isalnum()) # True (contains letters and numbers)
print(text.islower()) # False (not all lowercase)
print(text.isupper()) # False (not all uppercase)
print(text.startswith("Py")) # True
print(text.endswith("23")) # True
String Formatting
Python offers several ways to format strings:
1. Old-style formatting (% operator):
name = "Alice"
age = 25
# Old-style formatting
text = "My name is %s and I am %d years old." % (name, age)
print(text) # "My name is Alice and I am 25 years old."
2. str.format() method:
name = "Alice"
age = 25
# Using format() method
text = "My name is {} and I am {} years old.".format(name, age)
print(text)
# With positional arguments
text = "My name is {0} and I am {1} years old.".format(name, age)
print(text)
# With keyword arguments
text = "My name is {name} and I am {age} years old.".format(name=name, age=age)
print(text)
3. f-strings (Python 3.6+):
name = "Alice"
age = 25
# f-strings (most modern and recommended)
text = f"My name is {name} and I am {age} years old."
print(text)
# f-strings with expressions
result = f"The sum of 2 + 3 is {2 + 3}"
print(result)
# f-strings with formatting
pi = 3.14159
text = f"Pi is approximately {pi:.2f}"
print(text) # "Pi is approximately 3.14"
String Immutability
Strings are immutable, meaning you cannot modify them directly:
# This will cause an error
text = "Hello"
# text[0] = "h" # TypeError: 'str' object does not support item assignment
# Instead, create a new string
text = "Hello"
new_text = "h" + text[1:]
print(new_text) # "hello"
Escape Sequences
Escape sequences allow you to include special characters in strings:
| Escape Sequence | Description |
|---|---|
| \\ | Backslash |
| \' | Single quote |
| \" | Double quote |
| \n | New line |
| \t | Tab |
| \r | Carriage return |
| \b | Backspace |
# Escape sequences
print("Hello\nWorld") # New line
print("Hello\tWorld") # Tab
print("He said, \"Hello\"") # Double quotes inside string
print('It\'s a beautiful day') # Single quote inside string
Raw Strings
Raw strings treat backslashes as literal characters:
# Raw strings
normal_string = "C:\\Users\\Documents\\file.txt"
raw_string = r"C:\Users\Documents\file.txt"
print(normal_string) # "C:\Users\Documents\file.txt"
print(raw_string) # "C:\Users\Documents\file.txt"
Best Practices
When working with strings:
- Use f-strings for string formatting (Python 3.6+)
- Use
join()for concatenating multiple strings - Be aware of string immutability
- Use appropriate string methods for manipulation
- Consider encoding when working with different character sets
- Use raw strings for file paths and regular expressions
Strings are fundamental to Python programming. Mastering string operations will help you handle text data effectively in your programs.