4.3. String operations
Table of Contents
Working with Strings in Python
In this chapter, you’ll learn how to do useful operations with strings: combining them, repeating them, checking their length, and picking out parts of them.
Assume you already know what a string is and how to store it in a variable (covered in the str chapter).
Throughout this chapter we’ll use examples like:
message = "Hello"
name = "Alice"Concatenation: Joining Strings Together
Concatenation means joining strings end to end.
Use the + operator to concatenate strings:
first_name = "Alice"
last_name = "Smith"
full_name = first_name + last_name
print(full_name) # AliceSmith
full_name_with_space = first_name + " " + last_name
print(full_name_with_space) # Alice SmithYou can concatenate:
- variables that hold strings
- string literals like
" ","!","Python"
Common mistake: trying to add a string and a number directly:
age = 30
# print("Age: " + age) # This causes an error!To fix this, convert the number to a string first (you’ll see more about this when combining text and variables):
age = 30
print("Age: " + str(age)) # Age: 30Repeating Strings with `*`
You can repeat a string multiple times using the * operator with an integer:
laugh = "ha"
print(laugh * 3) # hahaha
line = "-"
print(line * 10) # ----------This is useful for simple text effects:
title = "Python"
print("=" * 10)
print(title)
print("=" * 10)Finding the Length of a String: `len()`
Use len() to count how many characters are in a string:
word = "Python"
print(len(word)) # 6
empty = ""
print(len(empty)) # 0
space = " "
print(len(space)) # 1Remember:
- Spaces, punctuation, and symbols are all counted as characters.
len()returns anint.
Accessing Individual Characters (Indexing)
You can access a single character in a string using square brackets [] with an index.
- Indexing starts at 0.
- For the string
"Python": Pis index0yis index1nis index5
word = "Python"
print(word[0]) # P
print(word[1]) # y
print(word[5]) # nCommon mistakes:
- Using an index that’s too large causes an error:
word = "Hi"
# print(word[2]) # Error: index out of range- Trying to change a character directly:
text = "cat"
# text[0] = "b" # This is NOT allowedStrings are immutable (you can’t change them in place). To “change” them, you build a new string (shown later in this chapter).
Negative Indexing (From the End)
You can also count from the end of the string using negative indices:
-1is the last character-2is the second-to-last, and so on
For "Python":
nis-1ois-2Pis-6
word = "Python"
print(word[-1]) # n
print(word[-2]) # o
print(word[-6]) # PSlicing: Getting Substrings
A slice is a part of a string. Use:
string[start:end]start= index where the slice begins (inclusive)end= index where the slice stops (exclusive, not included)
For "Python":
string[0:2]gives"Py"string[1:4]gives"yth"
Examples:
text = "Python programming"
print(text[0:6]) # Python
print(text[7:18]) # programming
# from index 7 up to (but not including) index 11
print(text[7:11]) # prog
You can omit start or end:
- Omit
start→ slice from the beginning - Omit
end→ slice to the end
text = "Hello, world!"
print(text[:5]) # Hello (from start to index 5, not included)
print(text[7:]) # world! (from index 7 to the end)
print(text[:]) # Hello, world! (whole string)Negative Indices in Slices
You can combine slicing with negative indices:
text = "Hello, world!"
# last 6 characters
print(text[-6:]) # world!
# everything except last character
print(text[:-1]) # Hello, world
# slice using negative start and end
print(text[-6:-1]) # worldBasic String Methods
Strings have methods—functions that belong to the string object.
You call them with dot notation: string.method().
Here are some useful basic methods. They return new strings; they don’t change the original.
Changing Case: `lower()`, `upper()`, `title()`
text = "Hello, World!"
print(text.lower()) # hello, world!
print(text.upper()) # HELLO, WORLD!
print(text.title()) # Hello, World!The original string stays the same:
print(text) # Hello, World!Removing Extra Spaces: `strip()`, `lstrip()`, `rstrip()`
These methods remove spaces (and some other whitespace) from the ends of a string.
raw = " Python "
print("[" + raw + "]") # [ Python ]
print("[" + raw.strip() + "]") # [Python]
print("[" + raw.lstrip() + "]") # [Python ]
print("[" + raw.rstrip() + "]") # [ Python]Counting and Finding Text: `count()`, `find()`
count(sub) tells you how many times a substring appears:
text = "banana"
print(text.count("a")) # 3
print(text.count("na")) # 2
find(sub) gives the index where a substring first appears, or -1 if not found:
text = "Hello, world!"
print(text.find("world")) # 7
print(text.find("Python")) # -1Replacing Text: `replace()`
replace(old, new) returns a new string with all old parts replaced by new:
text = "I like cats. Cats are cute."
new_text = text.replace("cats", "dogs")
print(new_text) # I like dogs. Cats are cute.
new_text2 = text.replace("Cats", "Dogs")
print(new_text2) # I like cats. Dogs are cute.
Note: replacement is case-sensitive ("cats" ≠ "Cats").
Escaping Special Characters
Some characters have a special meaning in strings, like the quote characters and backslash.
Use the backslash \ to escape them.
Quotes Inside Strings
If your string uses double quotes outside, you can use single quotes inside (and vice versa) without escaping:
msg1 = "She said 'hello'."
msg2 = 'He replied "hi".'To use the same quote type inside and outside, escape the inner quotes:
msg = "She said \"hello\"."
print(msg) # She said "hello".New Lines and Tabs: `\n`, `\t`
Some escape sequences represent special characters:
\n→ new line\t→ tab
text = "First line\nSecond line"
print(text)
# First line
# Second line
columns = "Name\tAge"
print(columns)
# Name AgeConverting Between Strings and Numbers (Quick Overview)
When mixing text and numbers, you often need to convert between types:
str(x)→ turnxinto a stringint(s)→ convert stringsto an integer (if possible)float(s)→ convert stringsto a float (if possible)
You’ll use this heavily when combining text and variables, and for user input, but here’s a simple example focused on strings:
age = 25
# Convert number to string to join with +
message = "You are " + str(age) + " years old."
print(message)Simple String Exercises
Try these small tasks to get comfortable with string operations:
- Create a variable
word = "Python"and: - Print the first and last characters.
- Print the substring
"tho"using slicing. - Ask the user (using
input()) for their first and last name, then: - Create a full name with a space between them.
- Print it in uppercase.
- Print how many characters are in the full name (including the space).
- Given
text = " I love Python! ", print: - The text without leading and trailing spaces.
- The number of
"o"characters in the cleaned-up text. - The text with
"Python"replaced by"coding". - Create a simple “banner” for a title:
- Ask for a title (e.g.
"Welcome"). - Print a line of
*characters above and below the title.
The number of*should match the length of the title.
These exercises will give you practice with concatenation, repetition, slicing, string methods, and len().
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!