Strings
A string can be described as a ‘string of characters’. It’s essentially any text, numbers, symbols, or even spaces—wrapped in quotes. In Python, strings are immutable, meaning that once you create a string, you can’t change the characters inside it directly; you have to create a new one.
Creating a String
You can create a string by putting text inside single quotes (
'...') or double quotes ("..."). There is no difference between them, but it’s helpful if your text contains a quote mark.Example
name = "Gemini"
message = 'Hello World!'
long_text = """This is a multi-line string.
It can span across several lines."""
Slicing Strings
Slicing is like taking a “slice” out of a loaf of bread. You use square brackets
[] to grab a specific part of the string.- Indices start at 0 (the first character).
- Negative indices start from -1 (the last character).
Example
fruit = "Strawberry"
print(fruit[0:5]) # Output: Straw (starts at 0, goes up to but NOT including 5)
print(fruit[-5:]) # Output: berry (starts 5 from the end to the very end)
print(fruit[0:]) # Output: Straw (starts at 0, goes up to the very end)
print(fruit[:5]) # Output: Straw (starts at the beginning, goes up to but NOT including 5)
print(fruit[-5:-1]) # Output: berr (starts 5 from the end, goes up to but NOT including 1 from the end)
print(fruit[:]) # Output: Strawberry (the whole string)
print(fruit[2:8]) # Output: rawber (starts at 2, goes up to but NOT including 8)
print(fruit[3:-3]) # Output: wberr (starts at 3, goes up to but NOT including 3 from the end)
Steps in Slicing
You can add a third number to your slice, called a step. The formula is:
[start : stop : step].- Start: Where to begin.
- Stop: Where to end (not included).
- Step: How many characters to jump.
Example
numbers = "0123456789"
print(numbers[0:10:2]) # Output: 02468 (Every 2nd character)
print(numbers[::-1]) # Output: 9876543210 (A common trick to reverse a string)
Strip the Spaces
Sometimes strings come with messy spaces at the beginning or end (often from user input). The .strip() method cleans them up.
| Method | Description |
.strip() | Removes whitespace from both ends. |
.lstrip() | Removes whitespace from the left side only. |
.rstrip() | Removes whitespace from the right side only. |
Example
user_input = " hello "
print(user_input.strip()) # Output: "hello"
print(user_input.lstrip()) # Output: "hello "
print(user_input.rstrip()) # Output: " hello"
String Formatting
Formatting is the “fill-in-the-blanks” of coding. The modern way to do this is using f-strings (formatted strings). Just put an
f before the quotes and use curly braces {} for variables.Example
# This code defines a name and age, then prints a formatted introduction message.
name = "Alex"
age = 25
print(f"Hi, my name is {name} and I am {age} years old.")
# The output will be: Hi, my name is Alex and I am 25 years old.
Concatenate Strings
Concatenation is a fancy word for joining strings together. In Python, you simply use the
+ operator.Example
first = "Ice"
second = "Cream"
combined = first + " " + second
print(combined) # Output: "Ice Cream"
String Methods
Python has built-in “tools” (methods) to change how strings look. Note that these don’t change the original string; they return a new one. There are many string method options, but here are:
.upper(): MAKES IT ALL CAPS..lower(): makes it all lowercase..replace("old", "new"): Swaps one bit of text for another..find("x"): Tells you the index number where “x” first appears.
Example
my_string = "Hello, World!"
# Using string methods
upper_string = my_string.upper()
lower_string = my_string.lower()
replaced_string = my_string.replace("World", "Python")
found_index = my_string.find("W")
print(upper_string) # Output: "HELLO, WORLD!"
print(lower_string) # Output: "hello, world!"
print(replaced_string) # Output: "Hello, Python!"
# Demonstrating string methods in Python
print(found_index) # Output: 7
Escape Strings
What if you want to put a double quote inside a double-quoted string? You use an Escape Character, which is a backslash \. It tells Python, “The next character is special text, not code.” The following are few Escape Code:
| Escape Code | Result |
\" | Double Quote |
\' | Single Quote |
\n | New Line (moves text to the next line) |
\t | Tab (adds a big space) |
Example
print("He said, \"Python is awesome!\"")
# Output: He said, "Python is awesome!"
