Strings
A string is a sequence of characters used to represent text. Python strings are one of the most-used data types, and they come with a rich set of built-in tools for creating, inspecting, and transforming text.
Creating Strings
You can create a string using either single quotes or double quotes — both work identically in Python, so pick one style and stay consistent.
single = 'Hello'
double = "Hello"
sentence = "It's a great day" # double quotes let you include an apostrophe
Concatenation and Repetition
The + operator joins strings together, and * repeats a string a given number of times.
first = "Hello"
second = "World"
greeting = first + " " + second
print(greeting) # Hello World
print("ab" * 3) # ababab
Indexing and Slicing
Each character in a string has a position, or index, starting at 0. Square brackets access a single character; a colon inside the brackets extracts a slice, a range of characters.
s = "Python"
print(s[0]) # P, the first character
print(s[1:4]) # yth, characters at index 1, 2, 3 (index 4 is excluded)
print(s[:3]) # Pyt, from the start up to index 3
print(s[3:]) # hon, from index 3 to the end
print(s[-1]) # n, negative indexes count from the end
print(s[::-1]) # nohtyP, a step of -1 reverses the string
The general slice syntax is s[start:stop:step]: start is the first index included, stop is the first index excluded, and step controls the direction and stride — leaving any of them out uses a sensible default (start of string, end of string, or a step of 1).
Common String Methods
Strings come with many built-in methods for common text operations.
| Method | Description | Example |
|---|---|---|
.upper() | Converts to all uppercase | "hi".upper() → "HI" |
.lower() | Converts to all lowercase | "HI".lower() → "hi" |
.strip() | Removes leading/trailing whitespace | " hi ".strip() → "hi" |
.replace(a, b) | Replaces all occurrences of a with b | "cat".replace("c","b") → "bat" |
.split(sep) | Splits a string into a list | "a,b,c".split(",") → ['a','b','c'] |
.join(list) | Joins a list into one string | ",".join(['a','b']) → "a,b" |
.find(sub) | Returns the index of a substring, or -1 | "hello".find("l") → 2 |
Formatting with f-strings
The modern, preferred way to build a string from variables is an f-string: prefix the string with f and place variables directly inside curly braces.
name = "Sonu"
age = 28
print(f"Hello, {name}! You are {age} years old.")
Before f-strings became available, the same result was written with the older .format() method, which is more verbose:
print("Hello, {}! You are {} years old.".format(name, age))
Note: f-strings are generally preferred today because they are shorter, easier to read, and let you embed any expression, not just a variable name, directly inside the braces.
Strings Are Immutable
Once a string is created, it cannot be changed in place. Any method that appears to "modify" a string, such as .upper() or .replace(), actually returns a brand new string object and leaves the original untouched.
s = "hello"
s.upper()
print(s) # still "hello" -- the original string was never changed
s = s.upper() # you must reassign to keep the new value
print(s) # now "HELLO"
# trying to change a character directly raises an error:
# s[0] = 'x' -> TypeError: 'str' object does not support item assignment