THEORY AND PRACTICE
-
Input and Output Data
- Tasks
-
Conditions
- Tasks
-
For Loop
- Tasks
-
Strings
- Tasks
-
While Loop
- Tasks
-
Lists
- Tasks
-
Two-Dimensional Arrays
- Tasks
-
Dictionaries
- Tasks
-
Sets
- Tasks
-
Functions and Recursion
- Tasks
Lesson 4. Strings and String methods in python
Introduction to Python strings and their methods
The definition of strings in Python
A string (string, str) is a sequence of characters. Python treats everything you put in quotes as a string,
whether it's letters, numbers, punctuation marks, or spaces. This is one of the most fundamental and frequently used
data types.
The feature of strings is immutability
The key feature of strings in Python is that they are immutable (immutable). This means that after creating a string, you cannot change its individual characters. Any operation that "modifies" a string (for example, replacing a character or converting to another register) actually creates a new string in memory.
# An attempt to change a character in a string will result in an error
my_string = "hello"
#my_string[0] = 'H' # This will cause a TypeError: 'str' object does not support item assignment
# The correct way is to create a new row
new_string = "H" + my_string[1:]
print(new_string) # Output: Hello
String assignment in programming: data entry
Strings are the main way a program interacts with the user and the outside world. They are used for:
- Receiving data from the user (for example, through the
input()function). - Reading and writing data to files.
- Sending and receiving information over the network.
- Displays messages, errors, and program results.
# Example of receiving data from a user
user_name = input("Enter your name: ")
print("Hello, " + user_name + "!")
Creating and joining strings in Python
Using single quotes ('')
The easiest way to create a string is to enclose the text in single quotes.
string_one = 'This is a string in single quotes.'
print(string_one)
Using double quotes (" ")
Double quotes work exactly the same as single quotes.
string_two = "This is a string in double quotes."
print(string_two)
Differences between single and double quotes
The main difference is convenience. If you need to use a single quotation mark inside a string (for example, an apostrophe), it is more convenient to enclose the entire string in doubles, and vice versa.
# Single quotes can be freely used inside double quotes
quote_string = "He said, 'Hello, world!'"
print(quote_string)
# There are double quotes inside single quotes
another_quote = 'Quote: "To be or not to be."'
print(another_quote)
Triple quotes ("' "' and """ """)
Triple quotes (both single and double) have two superpowers.
Creating multi-line strings
The text enclosed in triple quotes can be placed on several lines, and all line breaks will be saved.
multi_line_string = """This is the first line.
This is the second line.
And this is the third indented one."""
print(multi_line_string)
Putting quotation marks inside a string
Inside triple quotes, you can freely use both single and double quotes without any problems.
complex_string = '''You can use "double" and "single" quotation marks in this string.'''
print(complex_string)
Creating and joining strings
Examples of creating various strings
Choosing the type of quotation marks is primarily a matter of convenience. Here are practical examples of when which type of quotation marks is better to use:
-
Single quotes (
'): Ideal for simple strings without enclosed quotes.simple_string = 'Just text.' print(simple_string) -
Double quotes (
"): Are indispensable if there is an apostrophe or a single quotation mark inside the string.# Using an apostrophe inside a string dialogue = "Don't worry, be happy!" print(dialogue) -
Triple quotes (
"""or"'): The best choice for multi-line text or when both single and double quotes occur inside the string.# Example with multiline and different quotation marks complex_quote = '''He said, "It's a beautiful day, isn't it?"''' print(complex_quote)
Escaped characters
What is character escaping
Escaping is a way to insert special characters into a string that cannot be simply typed. To do this, use the backslash
\, which tells Python that the character following it needs to be interpreted in a special way.
Basic special characters
Creating a new line in Python: \n
\n is a line break character.
new_line_example = "First line\nSecond line"
print(new_line_example)
# Output:
# The first line
# The second line
\t — tab
\t — inserts a tab character (usually several spaces).
tab_example = "Name:\tIndex"
print(tab_example)
# Output: Name: Alex
\ — backslash
To insert the \ character itself into a string, it must be escaped: \\.
slash_example = "File path: C:\\Users\\Public "
print(slash_example)
# Output: File path: C:\Users\Public
'is a single quotation mark
Allows you to insert a single quote into a string created using single quotes.
single_quote_example = 'This is an example of using \'single quotation marks\' inside.'
print(single_quote_example)
" is a double quotation mark
Similarly for double quotes.
double_quote_example = "He quoted: \"Long live Python!\"."
print(double_quote_example)
Why escaping is important
Escaping allows you to precisely control the contents of a string, including non-printable characters (like \n)
and characters that have special meaning for Python syntax (like quotation marks).
Escaped characters
Why is shielding important
Backslash escaping \ solves two key problems:
- Inserting non-printable characters: It allows you to add characters to a string that cannot be simply
entered from the keyboard, for example, a newline character (
\n) or tabs (\t). Without escaping, it would be impossible to control the formatting of text within a single line. - Disambiguation: It tells the Python interpreter that the next character should be taken literally,
not as part of the syntax. For example, in the line
'It\'s my life', the slash says that the apostrophe is part of the wordIt's, not the end of the line. Without it, Python would have seen the end of the line afterItand would have issued a syntax error.
String operations and functions in Python
Concatenation (operator +)
Concatenation is the "gluing" of strings.
Combining two or more strings
The + operator combines strings into one new one.
# Example of string concatenation in Python
str1 = "Hello, "
str2 = "world"
str3 = "!"
result = str1 + str2 + str3
print(result) # Conclusion: Hello, world!
String repetition (operator * in Python)
The * operator allows you to repeat a string a set number of times.
Repeating a string
Multiplying a string by an integer creates a new string consisting of repetitions of the original one.
# Example of repetition
laugh = "ha"
repeated_laugh = laugh * 5
print(repeated_laugh) # Output: hahahahaha
Indexing strings
Each character in a string has its own sequence number — index. Indexing allows you to access a single character.
Indexing from the beginning (starting from 0)
Python character numbering always starts with 0.
Negative indexing (from the end)
Index -1 corresponds to the last character, -2 corresponds to the penultimate character,
and so on.
# Example of accessing characters by index
word = "Python"
# P y t h o n
# 0 1 2 3 4 5
# -6 -5 -4 -3 -2 -1
first_char = word[0]
third_char = word[2]
last_char = word[-1]
pre_last_char = word[-2]
print(f"First character: {first_char}") # Output: First character: P
print(f"Third character: {third_char}") # Output: Third character: t
print(f"Last character: {last_char}") # Output: Last character: n
print(f"Penultimate: {pre_last_char}") # Output: Penultimate: o
String slices in Python
Slice is a powerful tool for obtaining a part of a string (substring).
Basics of slices: [start:stop]
The slice takes characters from the start index to the stop index, not including the stop itself.
Skip start or stop
[:stop]— a slice from the beginning tostop.[start:]— a slice fromstartto the end.[:]is a complete copy of the string.
Slice step [start:stop:step]
step specifies which step to take the characters from. For example, step 2 will take every
second character. Step -1 will flip the line.
# Examples of various cross-sections
s = "Orange"
# 0 1 2 3 4 5 6 7
# A p e l s I n
# Slice 1 to 4 (not including) index
print(s[1:4]) # Output: sang
# Slice from the beginning to the 5th index
print(s[:5]) # Output: Orange
# Slice from the 3rd index to the end
print(s[3:]) # Output: lsin
# Every second character
print(s[::2]) # Output: Aelc
# Flip the string (classic trick)
print(s[::-1]) # Output: Downslope
Looping through a string for
Iterating over the characters of a string
The for loop makes it easy to go through each character of the string in turn.
for char in "Python":
print(char)
Example of a search with a condition
You can use a loop to analyze a string, for example, to count vowels.
vowels = "aeeeeeeee"
my_text = "Sample text for analysis"
vowel_count = 0
for letter in my_text.lower(): # .lower() to take into account both 'A' and 'a'
if letter in vowels:
vowel_count += 1
print(f"Number of vowels: {vowel_count}") # Output: Number of vowels: 7
Looping through a string for
Iterating over the characters of a string
The for loop is the main way to process each character in a string sequentially. Python automatically
"goes through" the string from beginning to end, putting the next character in the loop variable at each step.
for char in "Python":
print(f"Current character: {char}")
Iterating through a string with a condition
Inside the loop, conditional operators (if, elif, else) can be used to analyze
each character and perform actions depending on this condition.
# Example: let's count only the numbers in a string
address = "Lenin St., house 25, building 3"
digit_count = 0
for symbol in address:
if symbol.isdigit(): # Check if the symbol is a digit
digit_count += 1
print(f"Digits found in the address: {digit_count}") # Conclusion: Numbers found in the address: 3
String methods in Python
Methods are built—in functions that can be called from a string object to perform various actions. Syntax: string.method().
Python string length: len()
len() is not a method, but a built—in function, but it is used with strings all the time. Returns the
number of characters in a string.
text = "Hello, World!"
print(len(text)) # Output: 13
lower() — lowercase translation
Returns a copy of the string where all characters have been converted to lowercase.
text = "HELLO WORLD!"
print(text.lower()) # Conclusion: Hello, world!
the upper() methodtranslates to uppercase
Returns a copy of the string where all characters are uppercase.
text = "hello world!"
print(text.upper()) # Conclusion: HELLO, WORLD!
the strip() method removes spaces
Removes whitespace characters (spaces, tabs, line breaks) from the beginning and end of the line.
Options: lstrip() (left), rstrip() (right).
text_with_spaces = " lots of spaces around the edges "
print(f"'{text_with_spaces.strip()}'") # Output: 'lots of spaces around the edges'
method replace(old, new) — substring replacement
Replaces all occurrences of the substring old with the substring new.
text = "I love apples, apples are very tasty."
print(text.replace("apples", "bananas"))
# Conclusion: I love bananas, bananas are very tasty.
method split(separator) — splitting the string
Splits a string into a list (list) of substrings using the specified separator separator.
If no separator is specified, it is separated by spaces.
csv_data = "Ivanov,Ivan,30,Moscow"
items = csv_data.split(',')
print(items) # Output: ['Ivanov', 'Ivan', '30', 'Moscow']
sentence = "This is a simple sentence"
words = sentence.split()
print(words) # Output: ['This', 'simple', 'sentence']
method join(iterable) — combining a list of strings
Collects the elements of a list (or other iterable object) into a single row, inserting between them the row from which the method was called.
words_list = ['Python', 'it', 'powerful']
separator = ' '
result = separator.join(words_list)
print(result) # Conclusion: Python is powerful
# The more common syntax
result_alt = " ".join(words_list)
print(result_alt) # Conclusion: Python is powerful
method find(substring) and rfind(substring) — substring search
find() searches for the first occurrence of substring and returns the index of its beginning.
rfind() searches from the end. If no substring is found, both methods return -1.
text = "alpha beta gamma beta"
print(text.find("beta")) # Output: 6 (finds the first occurrence)
print(text.rfind("beta")) # Output: 17 (finds the last occurrence)
print(text.find("delta")) # Output: -1 (not found)
method startswith(prefix) — checking the beginning of the string
Returns True if the string starts with the specified prefix, otherwise False.
filename = "document.pdf"
print(filename.startswith("doc")) # Output: True
print(filename.startswith("img")) # Output: False
method endswith(suffix) — checking line endings
Returns True if the string ends with the specified suffix, otherwise False.
filename = "image.jpg"
print(filename.endswith(".jpg")) # Output: True
print(filename.endswith(".png")) # Output: False
String verification methods
These methods return True or False, depending on the contents of the string.
method isalpha() — whether the string consists of only letters
print("Python".isalpha()) # Output: True
print("Python3".isalpha())# Output: False
method isdigit() — whether the string consists only of digits
print("12345".isdigit()) # Output: True
print("123a".isdigit()) # Output: False
method isalnum() — whether the string consists of letters and numbers
print("Python3".isalnum()) # Output: True
print("Python 3".isalnum())# Output: False (space is not a letter or a number)
method islower() — whether all characters are in lowercase
print("hello".islower()) # Output: True
print("Hello".islower()) # Output: False
method isupper() — whether all characters are uppercase
print("HELLO".isupper()) # Output: True
print("HellO".isupper()) # Output: False
method isspace() — whether the string consists of whitespace characters
print("\t\n".isspace()) # Output: True
print(" a ".isspace()) # Output: False
Usage example continue
The continue statement interrupts the current iteration of the loop and immediately proceeds to the next
one. It is useful when you need to skip processing of some elements.
# Print all characters except vowels
word = "tutorial"
vowels = "aowies"
a = ""
for letter in word:
if letter in vowels:
continue # If the letter is a vowel, skip the rest of the cycle and go to the next letter.
a+=letter
print(a)
The else block in the for
loop
In Python, the for and while loops can have the else block. This is a unique
feature that often confuses beginners, but is actually very useful.
When the else block is executed
The else block after the for loop is executed only in one case: if the loop ended naturally,
that is, it went through all its iterations and was not interrupted by the break operator.
Example of a loop with else without interruptions break
If the loop just ends, else will work.
for i in range(3):
print(f"Iteration {i}")
else:
print("The loop ended completely without interruptions.")
The behavior of else when using break is not executed
If the loop is interrupted by the break operator, the else block is not executed.
This makes it easy to determine if the cycle was completed ahead of schedule (for example, because something was found)
or if it went through to the end.
# Searching for a character in a string
my_string = "hello world"
char_to_find = 'x'
for char in my_string:
if char == char_to_find:
print(f"Character '{char_to_find}' found!")
break # Breaking the cycle because we found what we were looking for
else:
# This block will be executed only if the for loop has passed to the end and has not found a character
print(f"The character '{char_to_find}' was not found in the string.")
Now let's change char_to_find to 'w':
# Searching for a character in a string
my_string = "hello world"
char_to_find = 'w'
for char in my_string:
if char == char_to_find:
print(f"Character '{char_to_find}' found!")
break # Breaking the cycle because we found what we were looking for
else:
# This block will be executed only if the for loop has passed to the end and has not found a character
print(f"The character '{char_to_find}' was not found in the string.")
Please note that the message from the else block was not output because the loop was interrupted.
String formatting in Python
Formatting is the creation of strings based on a template with data substitution in it.
Operator % (old style)
Is considered obsolete, but it is still found in the old code.
# %s for string, %d for integer, %f for floating point number
name = "Alice"
age = 25
text = "Name: %s, Age: %d" % (name, age)
print(text) # Output: Name: Alice, Age: 25
The format()
method is more flexible and modern than %.
# Positional parameters
text1 = "Name: {}, Age: {}".format("Bob", 30)
print(text1) # Output: Name: Bob, Age: 30
# Named parameters
text2 = "Name: {name}, Age: {age}".format(name="Carl", age=42)
print(text2) # Output: Name: Carl, Age: 42
F-strings: formatting strings in Python
F-strings (formatted string literals) are the most modern, convenient and fastest way of formatting. The string starts
with the letter f before the quotation marks.
Inserting variables and expressions
You can insert variables and even evaluate expressions right inside {}.
name = "Diana"
age = 28
# Examples of using f-strings
print(f"Hello, my name is {name} and I am {age} years old.")
print(f"In 5 years I will be {age + 5} years old.")
print(f"My name is in uppercase: {name.upper()}.")
Number formatting: string conversion
F-strings and the format() method provide powerful tools for formatting numbers.
Rounding to a certain number of digits
:.2f means "floating point number, 2 decimal places".
pi = 3.14159265
print(f"The number of Pi with an accuracy of 2 digits: {pi:.2f}") # Output: 3.14
Field alignment and width
You can set the overall width of the field and the alignment.
value = 123
# :>10 - align to the right in a 10-character wide field
# :<10 - on the left
# :^10 - centered
print(f"|{value:>10}|") # Output: | 123|
print(f"|{value:<10}|") # Output: |123 |
print(f"|{value:^10}|") # Output: | 123 |
F-strings: Formatting strings in Python
F-strings (formatted string literals) are the most modern, readable, and productive way to format strings in Python
(starting with version 3.6). To create an f-string, simply put the letter f in front of the opening quotation
mark.
Inserting variables and expressions
The main advantage of f-strings is the ability to insert variables and even entire expressions directly into a string,
enclosing them in curly brackets {}.
name = "Elena"
age = 30
profession = "developer"
# Just insert the variables
print(f"Hi, my name is {name}.")
# Inserting expressions and results of calling methods
print(f"I am {age} years old, and my name is in uppercase: {name.upper()}.")
print(f"In 10 years I will be {age + 10} years old.")
print(f"I work as {profession.replace('developer', 'engineer')}.")
Formatting numbers and strings inside f-strings
F-strings allow you not only to insert values, but also to control their display using a special syntax inside curly
brackets, which follows the colon {value:format}.
Usage examples
Formatting numbers
You can easily control the representation of numbers, which is especially important for floating-point data.
Rounding to a certain number of characters
The syntax is used for rounding.Nf, where N is the number of decimal places.
pi_value = 3.1415926535
price = 50
print(f"The number of Pi with an accuracy of 3 digits: {pi_value:.3f}") # Output: 3.142 (mathematical rounding occurs)
print(f"Product price: ${price:.2f}") # Withdrawal: $50.00 (zeros are added)
Field alignment and width
You can set the minimum width of the field for displaying the value and how to align it. This is useful for creating neat tables or reports.
— left alignment— right alignment^— center alignment
item = "Apples"
quantity = 5
cost = 250.5
# Setting a 15-character wide field with left alignment
print(f"|{item:<15}|")
# Setting a 5-character wide field with center alignment
print(f"|{quantity:^5}|")
# Setting a 10-character wide field with right alignment and 2 decimal places
print(f"|{cost:>10.2f}|")
# All together in one line:
print(f"| {item:<15} | {quantity:^5} | {cost:>10.2f} |")
You can also specify a symbol to fill in the empty space by putting it before the alignment symbol.
code = "A45"
print(f"Product code: {code:->10}") # Output: Product code: -------A45
print(f"Product code: {code:*^10}") # Output: Product code: ***A45****
Additional topics
Multiline strings with triple quotes — practical applications
They are ideal for storing templates, such as HTML code, SQL queries, or emails.
user_id = 105
sql_query = f"""
SELECT
user_name,
email
FROM
users
WHERE
id = {user_id};
"""
print(sql_query)
Features of using quotation marks inside strings
Summary of ways to insert a quotation mark into a string:
- Use a different type of quotation marks for framing:
"This is a 'quote'" - Escape quote:
'This is a \'quote\" - Use triple quotes:
"'This is a "quote" and another "quote"."'
Practical tips and recommendations
- Prefer f-strings.: To format strings, always use f-strings if your Python version allows it (3.6+). This is the most readable and effective way.
- Keep in mind immutability: If you need to change a string many times in a loop (for example, add
one character at a time), it will be more efficient to collect the characters in a list, and at the end combine them
using the
.join()method. - Combine methods: Methods can be called in a chain. It's concise and effective.
# Example of a chain of methods
raw_input = "USERNAME \n"
# 1. Remove the spaces at the edges - "USERNAME"
# 2. Lower case - "username"
# 3. Replace the space with an underscore - "username"
clean_username = raw_input.strip().lower().replace(" ", "_")
print(clean_username) # Output: user_name
Table of methods for working with strings in Python
| Method | Description | Usage example |
|---|---|---|
| Case change | ||
s.capitalize() |
Makes the first letter of the string uppercase and all others lowercase. | s = 'hello world'
print(s.capitalize()) → Hello world |
s.lower() |
Converts all characters of the string to lowercase. | s = 'PYTHON'
print(s.lower()) → python |
s.upper() |
Converts all characters of the string to uppercase. | s = 'python'
print(s.upper()) → PYTHON |
s.title() |
Capitalizes the first letter of each word in the string. | s = 'hello world'
print(s.title()) → Hello World |
s.swapcase() |
Reverses the case of all letters in the string. | s = 'PyThOn'
print(s.swapcase()) → pYtHoN |
s.casefold() |
A more aggressive conversion to lowercase for comparison. | s = 'Straße'
print(s.casefold()) → strasse |
| Search and replace | ||
s.count(sub) |
Counts the number of disjoint occurrences of the substring sub. |
s = 'hello world'
print(s.count('l')) → 3 |
s.find(sub) |
Returns the index of the first occurrence of the substring sub. If not found, returns -1. |
s = 'python'
print(s.find('th')) → 2 |
s.rfind(sub) |
Returns the index of the last occurrence of the substring sub. |
s = 'hello, world'
print(s.rfind('o')) → 8 |
s.index(sub) |
Like find(), but it causes a ValueError error if the substring is not found. |
s = 'python'
print(s.index('on')) → 4 |
s.rindex(sub) |
Like rfind(), but it causes a ValueError error if the substring is not found. |
s = 'hello, world'
print(s.rindex('o')) → 8 |
s.replace(old, new) |
Replaces all occurrences of the substring old with new. |
s = 'I like cats'
print(s.replace('cats', 'dogs')) → I like dogs |
| Checks | ||
s.startswith(prefix) |
Checks whether the string starts with the specified prefix prefix. |
s = 'file.txt'
print(s.startswith('file')) → True |
s.endswith(suffix) |
Checks whether the string ends with the specified suffix suffix. |
s = 'image.jpg'
print(s.endswith('.jpg')) → True |
s.isalnum() |
True if all characters in the string are letters or numbers and the string is not empty. |
s = 'Python3'
print(s.isalnum()) → True |
s.isalpha() |
True if all characters in the string are letters and the string is not empty. |
s = 'Python'
print(s.isalpha()) → True |
s.isdigit() |
True if all characters in the string are numbers and the string is not empty. |
s = '12345'
print(s.isdigit()) → True |
s.islower() |
True if all letters in the string are in lowercase. |
s = 'python'
print(s.islower()) → True |
s.isupper() |
True if all letters in the string are uppercase. |
s = 'PYTHON'
print(s.isupper()) → True |
s.isspace() |
True if the string consists of only whitespace characters. |
s = ' \t\n'
print(s.isspace()) → True |
s.istitle() |
True if the string is a "header" (see title()). |
s = 'Hello World'
print(s.istitle()) → True |
| Separation and unification | ||
s.split(sep=None) |
Splits the string using the separator sep and returns a list of strings. By default, sep is any space character. |
s = 'one,two,three'
print(s.split(',')) → ['one', 'two', 'three'] |
s.rsplit(sep=None) |
Divides the line, starting from the right. | s = 'a-b-c-d'
print(s.rsplit('-', 2)) → ['a-b', 'c', 'd'] |
s.splitlines() |
Separates a string by line breaks. | s = 'line1\nline2'
print(s.splitlines()) → ['line1', 'line2'] |
sep.join(iterable) |
Combines the elements of the iterable list into a single line using sep as a separator. |
words = ['Python', 'is', 'fun']
print(' '.join(words)) → Python is fun |
s.partition(sep) |
Divides a string by the first occurrence of sep into a tuple of three parts: before sep,
itself sep and after sep. |
s = 'user@domain.com'
print(s.partition('@')) → ('user', '@', 'domain.com') |
| Deleting characters | ||
s.strip(chars) |
Deletes the specified characters chars (whitespace by default) from the beginning and end of the string. |
s = ' _hello_ '
print(s.strip()) → _hello_
print(s.strip(' _')) → hello |
s.lstrip(chars) |
Deletes the specified characters chars from the beginning of the string. |
s = '___spam___'
print(s.lstrip('_')) → spam___ |
s.rstrip(chars) |
Deletes the specified characters chars from the end of the string. |
s = '___spam___'
print(s.rstrip('_')) → ___spam |
| Formatting and alignment | ||
s.center(width, fill) |
Centers the row by adding the fill character on the sides until the width width is reached. |
s = 'OK'
print(s.center(10, '*')) → ****OK**** |
s.ljust(width, fill) |
Aligns the row to the left. | s = 'text'
print(s.ljust(10, '.')) → text...... |
s.rjust(width, fill) |
Aligns the row to the right. | s = 'text'
print(s.rjust(10, '.')) → ......text |
s.zfill(width) |
Complements the string with zeros from the left to the length width. |
s = '42'
print(s.zfill(5)) → 00042 |
s.format(*args) |
Formats the string by inserting values into the fields marked with {}. |
s = 'Hello, {}!'
print(s.format('world')) → Hello, world! |