String
A string in Python is a sequence of characters used to store and manipulate text. Strings are one of the most commonly used data types in Python and are immutable, meaning their values cannot be changed after creation.
How to Create Strings
You can create strings using:
- Single quotes (').
- Double quotes (").
- Triple quotes (''' or """) for multi-line strings.
Examples:
# Single quotes string1 = 'Hello' # Double quotes string2 = "World" # Triple quotes for multi-line strings string3 = '''This is a multi-line string.''' print(string1, string2, string3)
Accessing String Characters
Strings in Python are indexed, meaning you can access individual characters using their position.
Examples:
text = "Python" # Access the first character print(text[0]) # Output: P # Access the last character print(text[-1]) # Output: n # Access a range of characters (slicing) print(text[0:3]) # Output: Pyt
String Methods
Python provides many built-in methods to work with strings.
Method | Description | Example |
---|---|---|
lower() | Converts all characters to lowercase | "HELLO".lower() → 'hello' |
upper() | Converts all characters to uppercase | "hello".upper() → 'HELLO' |
strip() | Removes leading and trailing spaces | " hello ".strip() → 'hello' |
replace(old, new) | Replaces all occurrences of a substring | "hello world".replace("world", "Python") → 'hello Python' |
split(delimiter) | Splits a string into a list using a delimiter | "a,b,c".split(",") → ['a', 'b', 'c'] |
join(iterable) | Joins elements of an iterable into a string | ",".join(['a', 'b', 'c']) → 'a,b,c' |
startswith() | Checks if a string starts with a specific substring | "hello".startswith("he") → True |
endswith() | Checks if a string ends with a specific substring | "hello".endswith("o") → True |
find(substring) | Returns the index of the first occurrence of a substring | "hello".find("e") → 1 |
count(substring) | Counts occurrences of a substring in the string | "banana".count("a") → 3 |
String Concatenation
You can combine strings using the + operator or format them using f-strings.
Examples:
# Concatenation greeting = "Hello" + " " + "World" print(greeting) # Output: Hello World # Using f-strings (Python 3.6+) name = "Alice" age = 25 message = f"My name is {name}, and I am {age} years old." print(message) # Output: My name is Alice, and I am 25 years old.
String Length
Use the len() function to get the length of a string.
Example:
text = "Python" print(len(text)) # Output: 6
String Iteration
You can iterate over a string using a loop.
Example:
text = "Python" for char in text: print(char)
Output:
P
y
t
h
o
n
String Slicing
You can extract parts of a string using slicing.
Examples:
text = "Python Programming" # Slice a substring print(text[0:6]) # Output: Python # Slice with a step print(text[0:6:2]) # Output: Pto # Reverse a string print(text[::-1]) # Output: gnimmargorP nohtyP
Escape Characters
Use escape sequences to include special characters in a string.
Escape Sequence | Description |
---|---|
\' | Single quote |
\" | Double quote |
\\ | Backslash |
\n | New line |
\t | Tab |
Example:
text = "This is a \"Python\" tutorial.\nLet's learn!" print(text)
Output:
This is a "Python" tutorial.
Let's learn!
String Immutability
Strings are immutable, meaning their values cannot be changed. Any operation that modifies a string creates a new string.
Example:
text = "hello" text = text.upper() # Creates a new string print(text) # Output: HELLO