Strings in Python are a sequence of characters enclosed in either single ('
) or double ("
) quotes, and Python provides a wide variety of built-in methods that allow you to manipulate and interact with them. In this lesson, you'll learn about some common string methods that you can use to modify, format, and analyze strings.
You can create strings using either single or double quotes.
string1 = "Hello, World!"
string2 = 'Python is fun!'
Both of these are valid string declarations.
You can access individual characters in a string using indexing (0-based index). The index starts from 0
for the first character and -1
for the last character.
word = "Python"
print(word[0]) # Output: P
print(word[-1]) # Output: n (last character)
word[0]
accesses the first character of the string.word[-1]
accesses the last character of the string.Use slicing to extract substrings from a string. Slicing uses the format string[start:end:step]
, where the start index is inclusive, the end index is exclusive, and step (optional) defines the stride between characters; it defaults to 1, meaning it extracts every character between start and end..
substring = word[0:3] # Extract characters from index 0 to 2
print(substring) # Output: Pyt
word[0:3]
extracts characters from index 0
to 2
(not including index 3
).Slicing uses the format string[start:end:step]
, where:
For example:
string[1:5]
extracts the substring from index 1 to index 4 (inclusive of 1, exclusive of 5).string[::2]
extracts every second character from the entire string.string[::-1]
reverses the string.Let me know if you want more examples or explanations!
Python provides several built-in string methods to manipulate and interact with strings. Below are some common ones:
len()
The len()
function returns the length (number of characters) of the string.
word = "Python"
print(len(word)) # Output: 6
lower()
The lower()
method converts all characters in a string to lowercase.
text = "Hello, World!"
print(text.lower()) # Output: hello, world!
upper()
The upper()
method converts all characters in a string to uppercase.
text = "Hello, World!"
print(text.upper()) # Output: HELLO, WORLD!
capitalize()
The capitalize()
method capitalizes the first character of the string and converts all other characters to lowercase.
text = "hello, world!"
print(text.capitalize()) # Output: Hello, world!
title()
The title()
method capitalizes the first letter of each word in the string.
text = "hello, world!"
print(text.title()) # Output: Hello, World!
strip()
The strip()
method removes leading and trailing whitespace (spaces, tabs, newlines) from a string.
text = " Hello, World! "
print(text.strip()) # Output: Hello, World!
replace()
The replace()
method replaces a specified substring with another substring.
text = "Hello, World!"
new_text = text.replace("World", "Python")
print(new_text) # Output: Hello, Python!
split()
The split()
method splits a string into a list based on a specified delimiter (space by default).
text = "Hello, World!"
words = text.split()
print(words) # Output: ['Hello,', 'World!']
join()
The join()
method joins a list of strings into a single string, using the specified separator.
words = ["Hello", "Python", "World"]
text = " ".join(words)
print(text) # Output: Hello Python World
find()
The find()
method returns the index of the first occurrence of a specified substring. If the substring is not found, it returns -1
.
text = "Hello, World!"
index = text.find("World")
print(index) # Output: 7
count()
The count()
method returns the number of occurrences of a substring in the string.
text = "Hello, World! Hello again!"
count = text.count("Hello")
print(count) # Output: 2
startswith()
The startswith()
method checks if a string starts with a specified prefix. It returns True
if the string starts with the prefix, otherwise False
.
text = "Hello, World!"
print(text.startswith("Hello")) # Output: True
endswith()
The endswith()
method checks if a string ends with a specified suffix. It returns True
if the string ends with the suffix, otherwise False
.
text = "Hello, World!"
print(text.endswith("!")) # Output: True
format()
The format()
method is used to format strings by inserting values into placeholders.
name = "Alice"
age = 30
text = "Hello, my name is {} and I am {} years old.".format(name, age)
print(text) # Output: Hello, my name is Alice and I am 30 years old.
f-strings provide a more readable and concise way to format strings, introduced in Python 3.6.
name = "Alice"
age = 30
text = f"Hello, my name is {name} and I am {age} years old."
print(text) # Output: Hello, my name is Alice and I am 30 years old.
You can also specify a delimiter to split the string on other characters.
word = "Python,Java,C++"
print(word.split(','))
# Output: ['Python', 'Java', 'C++']
Objective: Practice using string methods to manipulate and format strings.
Create a Python File:
Create a file named string_methods_practice.py
.
Format a Greeting:
Use the format()
method or f-strings to create a greeting message with your name and age.
Example:
name = "Alice"
age = 30
greeting = "Hello, my name is {} and I am {} years old.".format(name, age)
print(greeting)
Remove Whitespace:
Create a string with leading and trailing spaces, and use the strip()
method to remove them.
Example:
text = " Hello, World! "
print(text.strip())
Count Occurrences: Count how many times the word "Hello" appears in a given string.
Example:
text = "Hello, World! Hello again!"
print(text.count("Hello"))
Check Prefix/Suffix:
Use startswith()
and endswith()
to check if a string starts or ends with a specific word.
Example:
text = "Hello, World!"
print(text.startswith("Hello"))
print(text.endswith("!"))