The basics of working with lines in Python: creation, methods and manipulations with text data for information processing.

онлайн тренажер по питону
Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

A self-study guide for Python 3 compiled from the materials on this site. Primarily intended for those who want to learn the Python programming language from scratch.

Strings in Python are sequences of characters enclosed in single ('), double ("), or triple quotes ("' or """). Strings are used to represent text data and are one of the main data types in Python. In Python, strings are immutable, which means that they cannot be changed after creation.

What are strings in Python

A string in Python is an ordered sequence of Unicode characters. Strings can contain letters, numbers, special characters, and spaces. Each character in the string has its own index, starting from 0.

Creating strings in Python

Single and double quotes

You can create strings using single or double quotes. They are functionally equivalent, but their choice may depend on the contents of the string.

str1 = 'Hello, World!'
str2 = "Hello, World!"

print(str1)  # Hello, World!
print(str2)  # Hello, World!

Triple quotes for multiline strings

Triple quotes ("' or """) are used to create multi-line strings or strings containing quotation marks inside.

str3 = """This
multiline
string"""

str4 = '''This string contains "quotation marks" inside "'

print(str3)
print(str4)

Escaped characters in strings

Escaped characters allow you to include special characters in a string using a backslash ().

newline = "First line\Second line"
tabbed = "First line\Second line"
escaped_quote = "He said, "Hello!\""

print(newline)
print(tabbed)
print(escaped_quote)

Basic escaped characters

  • \n line feed
  • \t tabulation
  • \\ backslash
  • \' - single quotation mark
  • \" - double quotation mark
  • \r carriage return
  • \b backspace

String operations in Python

String concatenation

String concatenation is performed using the + operator.

str1 = "Hello"
str2 = "World"
str3 = str1 + ", " + str2 + "!"
print(str3)  # Hello, World!

Repeating lines

Lines can be repeated using the * operator.

str1 = "Hi! "
str2 = str1 * 3
print(str2)  # Hi! Hi! Hi! 

Indexing of rows

Each character of the string has an index starting from 0. Negative indexes are counted from the end of the string.

str1 = "Hello"
print(str1[0])   # H
print(str1[-1])  # o
print(str1[1])   # e
print(str1[-2])  # l

Slicing lines

Slices allow you to extract parts of a string using the [start:end:step] syntax.

str1 = "Hello, World!"
print(str1[0:5])    # Hello
print(str1[7:])     # World!
print(str1[:5])     # Hello
print(str1[::2])    # Hlo ol!
print(str1[::-1])   # !dlroW ,olleH

Iterating through a line in a loop

text = "1516 the best"
for i in range(len(text)):
    if text[i] in "1234567890":
        print(text[i])
# Output: 1, 5, 1, 6

# A more elegant way
for char in text:
    if char.isdigit():
        print(char)

String methods in Python

a table with basic methods and functions for working with strings in Python:

Stitching methods

method

The Description Example
upper() Convert to a real registry "hello".upper(upper) "HELLO"
downgrade() Convert to lowercase "HELLO".downgrade() "hello"
capitalized() Capitalizes the first letter "hello".in capital letters() "Hello"
header() Makes the main book of every word "hello, world".title() "Hello world"
swapcase() Changes the character logger "Hello".swapcase() "Hello"
stripe() You had problems from beginning to end "hello".strip() "hello"
lstrip() Do you have any suggestions? "hello ".lstrip() "hello"
rstrip() Gives you the opportunity to save money "hello".rstrip() "hello"
split() Splits a string into fragments "a,b,c".split(",")["a", "b", "c"]
join() Join the line monitoring ",".join(["a", "b", "c"])"a,b,c"
replace() Replace substring "hello".replace("l", "x") "hexxo"
find() Find the subscript "hello".find ("l") 2
rfind() Find the next search engine "hello".rfind("l") 3
index() Find the index (the same as it was before) "hello".index("l") 2
rindex() Find the next Yandex (Russian) "hello".index("l") 3
count() Calculates the number of expected "hello".quantity("L") 2
starts with() Start over "hello".it starts with ("he") True
ends with () Checks the end of the line "hello".ends with ("lo") True
isdigit() Check whether to restore due to "123".isdigit() True
isalpha() Check whether to install it from the book "abc".isalpha() True
isalnum() Check whether to set a password from the book "abc123".isalnum() True
isspace() Check whether to create spaces " ".isspace() True
islower() Checks the lower registrar "hello".islower() True
isupper() Check the authentic registry "HELLO".isupper() True
istitle() Contains uppercase letters of words "Hello, world".istitle() True
center() Centers the row "hello".Center(10) "hello "
ljust() Outputs on the left edge "hello".Total(10) "hello"
rjust() It is displayed on the right edge "hello".Just now(10) "hello"
zfill() Fills words with zeros "42".fill in(5) "00042"
encode() Encodes a string in a byte "hello".encode("utf-8") "hello"
format() Formats the string "Hello {}".format("World") "Hello world"
format_map() Formulates using a dictionary "Hello {name}".format_map({"name": "World"})
partition() Divides the string into 3 parts "a-b-c".section("-") ("a", "-", "b-c")
rpartition() Divided into 3 parts "a-b-c".section("-") ("a-b", "-", "c")
splitlines() Divides by lines "a\nb\nc".dividing lines() ["a", "b", "c"]
expandtabs() Replaces tabs with spaces "a\tb".expand the tabs(4) "a b"
translate() Translate characters according to the table "hello".translate(str.maketrans("l", "x")) "hexxo"
casefold() System guide to the lower registrar "Hello".casefold() "hello"

Built-in modules for working with pages

character

Case change

str1 = "Hello, World!"
print(str1.lower())      # hello, world!
print(str1.upper())      # HELLO, WORLD!
print(str1.title())      # Hello, World!
print(str1.capitalize()) # Hello, world!

Removing spaces

str1 = "   Hello, World!   "
print(str1.strip())      # "Hello, World!"
print(str1.lstrip())     # "Hello, World!   "
print(str1.rstrip())     # "   Hello, World!"

Substitution of substrings

str1 = "Hello, World!"
print(str1.replace("World", "Python"))  # Hello, Python!
print(str1.replace("l", "L", 2))        # HeLLo, World!

Splitting and combining lines

str1 = "Hello, World!"
list1 = str1.split(", ")
print(list1)  # ['Hello', 'World!']

str2 = ", ".join(list1)
print(str2)  # Hello, World!

# Line splitting
multiline = "line1\nline2\nline3"
lines = multiline.splitlines()
print(lines) # ['line1', 'line2', 'line3']

Substring search

str1 = "Hello, World!"
print(str1.find("o"))        # 4
print(str1.rfind("o"))       # 8
print(str1.find("Python"))   # -1
print(str1.index("World"))   # 7
print(str1.count("l"))       # 3

Checking the beginning and end of a line

str1 = "Hello, World!"
print(str1.startswith("Hello"))  # True
print(str1.endswith("World!"))   # True
print(str1.startswith("Hi"))     # False

String verification methods

Checking the contents of the string

str1 = "Hello"
str2 = "12345"
str3 = "Hello123"
str4 = "   "

print(str1.isalpha())   # True - only letters
print(str2.isdigit()) # True - numbers only
print(str3.isalnum()) # True - letters and numbers
print(str4.isspace()) # True - spaces only

Checking the register

str1 = "hello"
str2 = "HELLO"
str3 = "Hello World"

print(str1.islower())   # True
print(str2.isupper())   # True
print(str3.istitle())   # True

Additional checks

str1 = "123"
str2 = "hello123"
str3 = "HELLO123"

print(str1.isdecimal())      # True
print(str1.isnumeric())      # True
print(str2.isidentifier())   # True
print(str3.isprintable())    # True

Formatting strings in Python

Old formatting style (%)

name = "Alice"
age = 25
str1 = "My name is %s and I am %d years old." % (name, age)
print(str1)  # My name is Alice and I am 25 years old.

Format() method

name = "Alice"
age = 25
str1 = "My name is {} and I am {} years old.".format(name, age)
print(str1)  # My name is Alice and I am 25 years old.

# With named parameters
str2 = "My name is {name} and I am {age} years old.".format(name=name, age=age)
print(str2)

F-strings is the recommended method

F-strings (formatted string literals) are the most modern and convenient way to format strings in Python 3.6+.

name = "Alice"
age = 25
str1 = f"My name is {name} and I am {age} years old."
print(str1)  # My name is Alice and I am 25 years old.

Formatting numbers

pi = 3.14159
price = 1234.56

print(f"The number of Pi: {pi:.2f}")          # Number of Pi: 3.14
print(f"Price: {price:.2f}")           # Price: 1234.56
print(f"Price: {price:,.2f}")          # Price: 1,234.56
print(f"Percentage: {0.95:.2%}")         # Percentage: 95.00%

Working with multi-line lines

# Multiline string
poem = """The roses are red,
Violets are blue,
Python is great,
And that's the truth."""

print(poem)

# Usage for
def documentation is my_function():
"""
This is a multi-line documentation of a function.
    It may contain a detailed description
    parameters and return values.
    """
    pass

String encoding and decoding

# Encoding a string into bytes
text = "Hello world!"
encoded =text.encode('utf-8')
print(encoded) # b'\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82, \xd0\xbc\xd0\xb8\xd1\x80!'

# Decoding bytes into a string
decoded = encoded.decode('utf-8')
print(decoded) # Hello world!

Practical examples of working with strings

Email verification

email = "user@example.com"
if "@" in email and "." in email:
    print("Email is correct")

Counting characters

text = "Hello World"
vowels = "aeiouAEIOU"
vowel_count = sum(1 for char in text if char in vowels)
print(f"Number of vowels: {vowel_count}")

Clearing the line

text = "  Hello,    World!  "
cleaned = " ".join(text.split())
print(cleaned)  # "Hello, World!"

Strings in Python provide powerful features for working with text data. Understanding the basic methods and operations with strings is a fundamental skill for any Python developer. Regular use of these methods will help you efficiently process and manipulate text data in your projects.

 

 
Link Description Example
len() Creates a long string len("hello")5
str() Convert to a string str(123) "123"
repr() Creates a representation of a string repr("hello") "'hello'"
ord() Uses the Unicode code for the ord("A")65
chr() Reproduces the unicode encoding chr(65) "A"
ascii() Reproduces the ASCII representation ascii("h\\xe9llo") "'h\\xe9llo'"
bin() Convert to a double string cell(10) "0b1010"
oct() Convert to a comprehensive string October(10) "0o12"
hexadecimal() Convert to a virtual string hexadecimal(10) "0xa"
format() Formulates the meaning format(3.14, ".2f")"3.14"
sorted() Compile character strings sorted("hello") ['e', 'h', 'l', 'l', 'o']
reverse() Creates a shared editor list (inverted ("hello")) ['o', 'l', 'l', 'e', 'h']
list() Causes a pair (index, symbol) list(list("hello")) [(0, 'h'), (1, 'i')]
postal code() Connects zip code lines list of (postal code("abc", "123")) [('a', '1'), ('b', '2'), ('c', '3')]
map() Takes note of each figure list(map(ord, "abc"))[97, 98, 99]
filter() Filters characters by the condition list(filter(str.isalpha, "a1b2c"))['a', 'b', 'c']
any() Checks if there is True among the characters any(c.isdigit() for c in "a1b")True
all() Checks if all characters are True all(c.isalpha() for c in "abc")True
sum() Summarizes the character codes sum(ord(c) for c in "abc")294
min() Finds the minimum character min("hello")"e"
max() Finds the maximum character max("hello")"o"

Special methods for creating strings

method

The Description Example
str.maketrans() Creates a translation table str.maketrans("abc", "123")
bytes.decode() Decodes bytes into a string b"hello".decode("utf-8")"hello"
bytearray.decode() Decodes an array of bytes bytearray(b"hello").decode()"hello"

This table covers the main methods and functions for working with strings in Python. Each method has its own purpose and can be useful in various situations when processing text data.

 

 

Determining the length of a string

The len() function returns the number of characters in a string.

str1 = "Hello"
print(len(str1))  # 5

categories

  • Introduction to Python
  • Python Programming Basics
  • Control Structures
  • Data Structures
  • Functions and Modules
  • Exception Handling
  • Working with Files and Streams
  • File System
  • Object-Oriented Programming (OOP)
  • Regular Expressions
  • Additional Topics
  • General Python Base