41 вопрос о работе со строками в python

Алан-э-Дейл       09.08.2023 г.

Python finding substrings

The , , and
methods are used to find substrings in a string. They return the index of the first occurrence
of the substring. The and methods search from the
beginning of the string. The and search from
the end of the string.

The difference between the and methods is that
when the substring is not found, the former returns -1. The latter raises
exception.

find(str, beg=0, end=len(string))
rfind(str, beg=0, end=len(string))
index(str, beg=0, end=len(string))
rindex(str, beg=0, end=len(string))

The str is the substring to be searched for. The parameter is the starting index, by
default it is 0. The parameter is the ending index. It is by default equal to the length
of the string.

substrings.py

#!/usr/bin/env python

# substrings.py

a = "I saw a wolf in the forest. A lone wolf."

print(a.find("wolf"))
print(a.find("wolf", 10, 20))
print(a.find("wolf", 15))

print(a.rfind("wolf"))

We have a simple sentence. We try to find the index of a substring
in the sentence.

print(a.find("wolf"))

The line finds the first occurrence of the substring ‘wolf’ in the sentence. It
prints 8.

print(a.find("wolf", 10, 20))

This line tries to find a ‘wolf’ substring. It starts from the 10th character
and searches the next 20 characters. There is no such substring in this
range and therefore the line prints -1, as for not found.

print(a.find("wolf", 15))

Here we search for a substring from the 15th character until the end of
the string. We find the second occurrence of the substring. The line
prints 35.

print(a.rfind("wolf"))

The looks for a substring from the end. It finds the
second occurrence of the ‘wolf’ substring. The line prints 35.

$ ./substrings.py
8
-1
35
35

This is the output.

In the second example, we will use the and
methods.

substrings2.py

#!/usr/bin/env python

# substrings2.py

a = "I saw a wolf in the forest. A lone wolf."

print(a.index("wolf"))
print(a.rindex("wolf"))

try:
    print(a.rindex("fox"))
except ValueError as e:
    print("Could not find substring")

In the example, we search for substrings with the
and methods.

print(a.index("wolf"))
print(a.rindex("wolf"))

These lines find the first occurrence of the ‘wolf’ substring from the
beginning and from the end.

try:
    print(a.rindex("fox"))
except ValueError as e:
    print("Could not find substring")

When the substring is not found, the method raises
exception.

$ ./substrings2.py
8
35
Could not find substring

This is the output of the example.

Unicode

Python поддерживает Unicode так как по дефолту в нём используется UTF-8

Это позволяет использовать юникод символы без заморочек

>>> «Pythonia voi käyttää myös vaativassa ja tieteellisessä»

‘Pythonia voi käyttää myös vaativassa ja tieteellisessä’

Если бы поддержки не было скорее всего пришлось бы заменять специальные символы, такие как умлауты, на из юникод представление

>>> «Pythonia voi k\u00e4ytt\u00e4\u00e4 my\u00f6s vaativassa ja tieteellisess\u00e4»

‘Pythonia voi käyttää myös vaativassa ja tieteellisessä’

Можно получить юникод символы и другими способами

‘\xe4’

‘ä’

bytes

>>> s = ‘abc’

>>> bytes(s, ‘utf-8’)

b’abc’

>>> s = ‘абв’

>>> bytes(s, ‘utf-8’)

b’\xd0\xb0\xd0\xb1\xd0\xb2′

а — \xd0\xb0

б — \xd0\xb1

в — \xd0\xb2

>>> s = ‘ä’

>>> bytes(s, ‘utf-8’)

b’\xc3\xa4′

ä — \xc3\xa4

>>> s = ‘абв’

>>> b = bytes(s, ‘utf-8’)

print(b)

b’\xd0\xb0\xd0\xb1\xd0\xb2′

>>> str(b)

Получится не совсем то, что нужно

«b’\xd0\xb0\xd0\xb1\xd0\xb2′»

А вот если добавить правильную кодировку, то абв снова появятся

>>> str(b, ‘utf-8’)

‘абв’

Указав неправильную кодировку можно получить какой-то неправильный результат

>>> str(b, ‘cp1251’)

‘абв’

Указав опцию b можно посмотреть содержимое файла, например изображения

>>> file = «/home/andrei/image.png»

>>> f = open(file, ‘rb’)

>>> f.read()

b’\x89PNG\r\n…

Подробнее в статье

«Работа с файлами в Python»

Basic String Functions

capitalize() It converts the first character of a string to uppercase
casefold() It converts any string to lower case irrespective of its case
center() It is used to center align the string
count() It is used to count the number of times a specific value appears in the string
endswith() It checks if the string is ending with specified value then it returns True
find() It is used to find the presence of a specified value in a string
index() It is used to find the first occurrence of a specified value in the string
isalnum() It checks if all the characters are alphanumeric then returns True
isalpha() It checks if all the characters are alphabet (a-z) then returns True
isdecimal() It checks if all the characters are decimals (0-9) then returns True
isdigit() It checks if all the characters are digits then returns True
islower() It checks if all the characters are in lowercase then returns True
isnumeric() It checks if all the characters are numeric (0-9) then returns True
isspace() It checks if all the characters are whitespaces then returns True
isupper() It checks if all the characters are in uppercase then returns True
lower() It is used to convert all characters to lowercase
partition() It is used to split the string into a tuple of three elements
replace() It is used to replace specified word or phrase into another word or phrase in the string
split() It is used to split a string into a list
splitlines() It is used to split the string and make a list of it. Splits at the line breaks.
startswith() It checks if the string is starting with specified value then it returns True
strip() It is used to remove characters specified in argument from both the ends )
swapcase() It is used to swap uppercase string to lowercase or vice versa
title() It converts initial letter of each word to uppercase
upper() It is used to convert all characters in a string to uppercase

Miscellaneous Functions that work on String

ascii() It returns a string containing the printable form of an object and ignores the non-ASCII values in the string
bool() It returns boolean value i.e. True or False for an object
bytearray() It returns an object containing an array of bytes provided through the input
bytes() It returns bytes object which cannot be modified and is a sequence of integers in the range from 0 to 255
enumerate() It is used to add a counter to an iterable and then returns its value
float() It returns floating-point number from the given argument
hash() It returns the hash value of the object, if applicable
id() It returns the specific identity of an object which is a unique integer
int() It returns an integer object from the given input and the base of the returned object will always be 10
len() It returns the length of sequence i.e. number of items in an object
map() It is used to apply a given function to every item of iterable which can be a tuple, list, etc. and also returns a list containing resultant values
ord() It accepts a string argument of single Unicode character and returns its respect Unicode point
print() It prints the provided object to any output device
slice() It creates an object which represents a set of indices specified by its range(start, stop, step)
type() It returns the object’s type

Python String Operations

There are many operations that can be performed with strings which makes it one of the most used data types in Python.

To learn more about the data types available in Python visit: Python Data Types

Concatenation of Two or More Strings

Joining of two or more strings into a single one is called concatenation.

The + operator does this in Python. Simply writing two string literals together also concatenates them.

The * operator can be used to repeat the string for a given number of times.

When we run the above program, we get the following output:

str1 + str2 =  HelloWorld!
str1 * 3 = HelloHelloHello

Writing two string literals together also concatenates them like + operator.

If we want to concatenate strings in different lines, we can use parentheses.

Iterating Through a string

We can iterate through a string using a for loop. Here is an example to count the number of ‘l’s in a string.

When we run the above program, we get the following output:

3 letters found

Built-in functions to Work with Python

Various built-in functions that work with sequence work with strings as well.

Some of the commonly used ones are and . The function returns an enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful for iteration.

Similarly, returns the length (number of characters) of the string.

When we run the above program, we get the following output:

list(enumerate(str) =  
len(str) =  4

Определение шага при создании срезов строк

В дополнение к двум индексам при создании срезов можно использовать третий параметр. Третий параметр указывает шаг, означающий, на сколько символов нужно сдвинуться после извлечения первого символа из строки. В предыдущих примерах мы не использовали параметр шага, а по умолчанию Python использует значение шага 1, выводя все символы между двумя индексами.

Давайте снова посмотрим на пример выше, который выводит подстроку “Shark”:

Мы можем получить те же результаты, добавив третий параметр шага со значением 1:

Если шаг равен 1, выводятся все символы между двумя индексами среза. Если мы опустим параметр шага, Python будет по умолчанию использовать значение 1.

Если же мы увеличим значение шага, некоторые символы будут пропущены:

Если мы зададим шаг 2 как последний параметр в синтаксисе Python , будет пропущен каждый второй символ. Выводимые символы обозначены красным цветом:

Sammy Shark!

Обратите внимание, что символ пробела с индексом 5 также пропускается, если задан шаг 2. Если мы используем более крупное значение шага, подстрока будет значительно короче:

Если мы используем более крупное значение шага, подстрока будет значительно короче:

Если мы укажем шаг 4 как последний параметр синтаксиса Python , будет выведен только каждый четвертый символ. Выводимые символы также обозначены красным цветом:

Sammy Shark!

В этом примере символ пробела тоже пропускается.

Поскольку мы выводим всю строку, мы можем опустить два индекса и оставить два двоеточия в синтаксисе, чтобы получить тот же результат:

Если мы пропустим два индекса и оставим запятые, мы включим в диапазон всю строку, а последний параметр будет определять шаг, то есть, количество пропускаемых символов.

Также мы можем указать отрицательное значение шага и использовать его для вывода исходной строки в обратном порядке, если зададим шаг -1:

Два двоеточия без параметров означают вывод всех символов первоначальной строки, шаг 1 означает вывод всех символов без пропуска, а отрицательное значение шага изменяет порядок вывода символов на противоположный.

Давайте повторим эту команду, но используем шаг -2:

В этом примере, , мы включаем в диапазон всю первоначальную строку, поскольку индексы не указаны, и задаем обратный порядок вывода отрицательным значением шага. Кроме того, с шагом -2 мы пропускаем каждую вторую букву строки, выводимой в обратном порядке:

! krahSymmaS

В этом примере выводится символ пробела.

Задавая третий параметр синтаксиса среза Python, мы указываем шаг подстроки, которую извлекаем из первоначальной строки.

Error handling

Either compile time or run time errors can occur when processing
f-strings. Compile time errors are limited to those errors that can be
detected when scanning an f-string. These errors all raise
SyntaxError.

Unmatched braces:

>>> f'x={x'
  File "<stdin>", line 1
SyntaxError: f-string: expecting '}'

Invalid expressions:

>>> f'x={!x}'
  File "<stdin>", line 1
SyntaxError: f-string: empty expression not allowed

Run time errors occur when evaluating the expressions inside an
f-string. Note that an f-string can be evaluated multiple times, and
work sometimes and raise an error at other times:

>>> d = {0:10, 1:20}
>>> for i in range(3):
...     print(f'{i}:{d}')
...
0:10
1:20
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: 2

or:

No use of globals() or locals()

In the discussions on python-dev , a number of solutions where
presented that used locals() and globals() or their equivalents. All
of these have various problems. Among these are referencing variables
that are not otherwise used in a closure. Consider:

>>> def outer(x):
...     def inner():
...         return 'x={x}'.format_map(locals())
...     return inner
...
>>> outer(42)()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in inner
KeyError: 'x'

This returns an error because the compiler has not added a reference
to x inside the closure. You need to manually add a reference to x in
order for this to work:

>>> def outer(x):
...     def inner():
...         x
...         return 'x={x}'.format_map(locals())
...     return inner
...
>>> outer(42)()
'x=42'

In addition, using locals() or globals() introduces an information
leak. A called routine that has access to the callers locals() or
globals() has access to far more information than needed to do the
string interpolation.

Python string formatting

String formatting is dynamic putting of various values into a string.
String formatting can be achieved with the operator or the
method.

oranges.py

#!/usr/bin/env python

# oranges.py

print('There are %d oranges in the basket' % 32)
print('There are {0} oranges in the basket'.format(32))

In the code example, we dynamically build a string. We put a number
in a sentence.

print('There are %d oranges in the basket' % 32)

We use the formatting specifier. The character
means that we are expecting an integer. After the string, we put a modulo operator
and an argument. In this case we have an integer value.

print('There are {0} oranges in the basket'.format(32))

The same task is achieved with the method. This time
the formatting specifier is .

$ ./oranges.py 
There are 32 oranges in the basket
There are 32 oranges in the basket

The next example shows how to add more values into a string.

fruits.py

#!/usr/bin/env python

# fruits.py

print('There are %d oranges and %d apples in the basket' % (12, 23))
print('There are {0} oranges and {1} apples in the basket'.format(12, 23))

In both lines, we add two format specifiers.

$ ./fruits.py 
There are 12 oranges and 23 apples in the basket
There are 12 oranges and 23 apples in the basket

In the next example, we build a string with a float and a string value.

height.py

#!/usr/bin/env python

# height.py

print('Height: %f %s' % (172.3, 'cm'))
print('Height: {0:f} {1:s}'.format(172.3, 'cm'))

We print the height of a person.

print('Height: %f %s' % (172.3, 'cm'))

The formatting specifier for a float value is and for a
string .

print('Height: {0:f} {1:s}'.format(172.3, 'cm'))

With the method, we add and
characters to the specifier.

$ ./height.py 
Height: 172.300000 cm
Height: 172.300000 cm

We might not like the fact that the number in the previous example has 6
decimal places by default. We can control the number of the decimal places
in the formatting specifier.

height2.py

#!/usr/bin/env python

# height2.py

print('Height: %.2f %s' % (172.3, 'cm'))
print('Height: {0:.2f} {1:s}'.format(172.3, 'cm'))

The decimal point followed by an integer controls the number of decimal places.
In our case, the number will have two decimal places.

$ ./height2.py 
Height: 172.30 cm
Height: 172.30 cm

The following example shows other formatting options.

various.py

#!/usr/bin/python

# various.py

# hexadecimal
print("%x" % 300)
print("%#x" % 300)

# octal
print("%o" % 300)

# scientific
print("%e" % 300000)

The first two formats work with hexadecimal numbers. The character
will format the number in hexadecimal notation. The character will add
to the hexadecimal number. The character shows the number in
octal format. The character will show the number in scientific format.

$ ./various.py 
12c
0x12c
454
3.000000e+05

The method also supports the binary format.

various2.py

#!/usr/bin/python

# various2.py

# hexadecimal
print("{:x}".format(300))
print("{:#x}".format(300))

# binary
print("{:b}".format(300))

# octal
print("{:o}".format(300))

# scientific
print("{:e}".format(300000))

The example prints numbers in hexadecimal, binary, octal, and scientific
formats.

The next example will print three columns of numbers.

columns1.py

#!/usr/bin/env python

# columns1.py

for x in range(1, 11):
    print('%d %d %d' % (x, x*x, x*x*x))

The numbers are left justified and the output is not optimal.

$ ./columns1.py 
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000

To correct this, we use the width specifier. The width specifier
defines the minimal width of the object. If the
object is smaller than the width, it is filled with spaces.

columns2.py

#!/usr/bin/env python

# columns2.py

for x in range(1, 11):
    print('%2d %3d %4d' % (x, x*x, x*x*x))

Now the output looks OK. Value 2 makes the first column to be 2 charactes wide.

$ ./columns2.py 
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000

Now we have the improved formatting with the method.

columns3.py

#!/usr/bin/env python

# columns3.py

for x in range(1, 11):
    print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))

This chapter of the Python tutorial was dedicated to the string data type in Python.

Contents
Previous
Next

How to access characters in a string?

We can access individual characters using indexing and a range of characters using slicing. Index starts from 0. Trying to access a character out of index range will raise an . The index must be an integer. We can’t use floats or other types, this will result into .

Python allows negative indexing for its sequences.

The index of refers to the last item, to the second last item and so on. We can access a range of items in a string by using the slicing operator (colon).

When we run the above program, we get the following output:

str =  programiz
str =  p
str =  z
str =  rogr
str =  am

If we try to access an index out of the range or use numbers other than an integer, we will get errors.

Slicing can be best visualized by considering the index to be between the elements as shown below.

If we want to access a range, we need the index that will slice the portion from the string.

String Slicing in Python

Python comparing strings

Comparing strings is a common job in programming. We can compare two strings
with the operator. We can check the opposite with the
non-equality operator. The operators return a boolean
or .

comparing.py

#!/usr/bin/env python

# comparing.py

print("12" == "12")
print("17" == "9")
print("aa" == "ab")

print("abc" != "bce")
print("efg" != "efg")

In this code example, we compare some strings.

print("12" == "12")

These two strings are equal, so the line returns .

print("aa" == "ab")

The first two characters of both strings are equal. Next the following characters
are compared. They are different so the line returns .

print("abc" != "bce")

Since the two strings are different, the line returns .

$ ./comparing.py
True
False
False
True
False

This is the output.

Python splitting and joining strings

A string can be split with the or the
method. They return a list of strings which
were cut from the string using a separator. The optional second
parameter is the maximum splits allowed.

splitting.py

#!/usr/bin/env python

# splitting.py

nums = "1,5,6,8,2,3,1,9"

k = nums.split(",")
print(k)

l = nums.split(",", 5)
print(l)

m = nums.rsplit(",", 3)
print(m)

We have a comma-delimited string. We cut the string into parts.

k = nums.split(",")

We split the string into eight parts using a comma as a separator.
The method returns a list of eight strings.

l = nums.split(",", 5)

Here we split the string into six parts. There are five substrings
and the remainder of the string.

m = nums.rsplit(",", 3)

Here we split the string into four parts. This time the splitting goes
from the right.

$ ./splitting.py



Strings can be joined with the string.
It returns a string concatenated from the strings passed as a parameter.
The separator between elements is the string providing this method.

split_join.py

#!/usr/bin/env python

# split_join.py

nums = "1,5,6,8,2,3,1,9"

n = nums.split(",")
print(n)

m = ':'.join(n)
print(m)

First we split a string into a list of strings. Then we
join the strings into one string with the elements being
separated by the provided character.

m = ':'.join(n)

The method creates one string from a list of
strings. The elements are separated by the character.

$ ./split_join.py

1:5:6:8:2:3:1:9

This is the output.

Another method which can be used for splitting strings is .
It will split the string at the first occurrence of the separator and return
a 3-tuple containing the part before the
separator, the separator itself, and the part after the separator.

partition.py

#!/usr/bin/env python

# partition.py

s = "1 + 2 + 3 = 6"

a = s.partition("=")

print(a)

We use the method in this example.

a = s.partition("=")

This will cut the string into three parts. One before the
character, the separator, and the right side after the separator.

$ ./partition.py
('1 + 2 + 3 ', '=', ' 6')

This is the output.

Переназначение строк

Обновить содержимое строк так же просто, как присвоить его новой строке. Строковый объект не поддерживает присвоение элемента, т. е. строка может быть заменена только новой строкой, поскольку ее содержимое не может быть частично заменено. Строки неизменяемы в Python.

Рассмотрим следующий пример.

Пример 1.

 
str = "HELLO"   
str = "h"   
print(str)   

Выход:

Traceback (most recent call last):
  File "12.py", line 2, in <module>
    str = "h";
TypeError: 'str' object does not support item assignment

Однако в примере 1 строку str можно полностью присвоить новому содержимому, это указано в следующем примере.

Пример 2.

 
str = "HELLO"   
print(str)   
str = "hello"   
print(str)   

Выход:

HELLO 
hello   

Форматирование строки Python

Управляющая последовательность

Предположим, нам нужно написать текст – They said, “Hello what’s going on?” – данный оператор может быть записан в одинарные или двойные кавычки, но он вызовет ошибку SyntaxError, поскольку он содержит как одинарные, так и двойные кавычки.

Рассмотрим следующий пример, чтобы понять реальное использование операторов Python.

 
str = "They said, "Hello what's going on?"" 
print(str) 

Выход:

SyntaxError: invalid syntax 

Мы можем использовать тройные кавычки для решения этой проблемы, но Python предоставляет escape-последовательность.

Символ обратной косой черты(/) обозначает escape-последовательность. За обратной косой чертой может следовать специальный символ, который интерпретируется по-разному. Одиночные кавычки внутри строки должны быть экранированы. Мы можем применить то же самое, что и в двойных кавычках.

Пример –

 
# using triple quotes  
print('''''They said, "What's there?"''')  
  
# escaping single quotes  
print('They said, "What\'s going on?"')  
  
# escaping double quotes  
print("They said, \"What's going on?\"")

Выход:

They said, "What's there?" 
They said, "What's going on?" 
They said, "What's going on?" 

Список escape-последовательностей приведен ниже:

Номер Последовательность Описание Пример
1. \newline Игнорирует новую строку
print("Python1 \
Python2 \
Python3")

Output:

Python1 Python2 Python3
2. \\ Косая черта
print("\\")

Output:

\
3. \’ одиночные кавычки
print('\'')

Output:

'
4. \\” Двойные кавычки
print("\"")

Output:

"
5. \a ASCII Bell
print("\a")
6. \b ASCII клавиша Backspace
print("Hello \b World")

Output:

Hello World
7. \f ASCII Formfeed
print("Hello \f World!")
Hello  World!
8. \n ASCII Linefeed
print("Hello \n World!")

Output:

Hello
 World!
9. \r ASCII Carriege Return(CR)
print("Hello \r World!")

Output:

World!
10. \t ASCII горизонтальный tab
print("Hello \t World!")

Output:

Hello 	 World!
11. \v ASCII вертикальный Tab
print("Hello \v World!")

Output:

Hello 
 World!
12. \ooo Символ с восьмеричным значением
print("\110\145\154\154\157")

Output:

Hello
13 \xHH Символ с шестнадцатеричным значением
print("\x48\x65\x6c\x6c\x6f")

Output:

Hello

Вот простой пример escape-последовательности.

 
print("C:\\Users\\DEVANSH SHARMA\\Python32\\Lib")  
print("This is the \n multiline quotes")  
print("This is \x48\x45\x58 representation") 

Выход:

C:\Users\DEVANSH SHARMA\Python32\Lib
This is the 
 multiline quotes
This is HEX representation 

Мы можем игнорировать escape-последовательность из данной строки, используя необработанную строку. Мы можем сделать это, написав r или R перед строкой. Рассмотрим следующий пример.

 
print(r"C:\\Users\\DEVANSH SHARMA\\Python32") 

Выход:

C:\\Users\\DEVANSH SHARMA\\Python32

Summary

  • In Python, a string is a series of characters. Also, Python strings are immutable.
  • Use quotes, either single-quotes or double-quotes to create string literals.
  • Use the backslash character to escape quotes in strings
  • Use raw strings to escape the backslash character.
  • Use f-strings to insert substitute variables in literal strings.
  • Place literal strings next to each other to concatenate them. And use the + operator to concatenate string variables.
  • Use the function to get the size of a string.
  • Use the to access the character at the position n of the string .
  • Use slicing to extract a substring from a string.

Разделение строк

Также мы можем вызвать ряд символов из строки. Допустим, мы хотим вывести слово . Для этого мы можем создать срез, представляющий собой последовательность символов в исходной строке. С помощью срезов мы можем вызывать несколько значений символов, создавая диапазоны символов, разделенные двоеточием :

При построении среза, такого как , первый индекс соответствует началу среза (включительно), а второй — окончанию среза (не включительно). Поэтому в нашем примере конец диапазона обозначается индексом позиции сразу после конца строки.

При разделении строк на срезы мы создаем подстроки, то есть, строки внутри других строк. Вызывая , мы вызываем подстроку , существующую в строке .

Если мы хотим включить любой конец строки, мы можем пропустить одно из чисел в синтаксисе . Например, если нам нужно вывести первое слово строки — “Sammy”, мы можем сделать это так:

Мы пропустили индекс перед двоеточием в синтаксисе среза и указали только индекс после двоеточия, обозначающий конец подстроки.

Чтобы вывести подстроку, начинающуюся в середине строки и идущую до конца строки, мы можем указать только индекс перед двоеточием:

Если мы укажем только индекс перед двоеточием и не укажем второй индекс, подстрока будет идти от соответствующего первому индексу символа до конца строки.

Для создания срезов также можно использовать отрицательные индексы. Как мы уже говорили раньше, отрицательные индексы строки начинаются с -1 и отсчитываются далее к началу строки. При использовании отрицательных индексов, мы начинаем с меньшего числа, потому что соответствующий ему символ идет раньше.

Давайте используем два отрицательных индекса для создания среза строки :

Подстрока “ark” выводится из строки “Sammy Shark!”, потому что символ “a” соответствует индексу -4, а символ “k” находится перед позицией индекса -1.

What is String in Python?

A string is a sequence of characters.

A character is simply a symbol. For example, the English language has 26 characters.

Computers do not deal with characters, they deal with numbers (binary). Even though you may see characters on your screen, internally it is stored and manipulated as a combination of 0s and 1s.

This conversion of character to a number is called encoding, and the reverse process is decoding. ASCII and Unicode are some of the popular encodings used.

In Python, a string is a sequence of Unicode characters. Unicode was introduced to include every character in all languages and bring uniformity in encoding. You can learn about Unicode from Python Unicode.

Гость форума
От: admin

Эта тема закрыта для публикации ответов.