V tomto kurzu se naučíte vytvářet, formátovat, upravovat a mazat řetězce v Pythonu. Také vás seznámí s různými řetězcovými operacemi a funkcemi.
Video: Python Strings
Co je řetězec v Pythonu?
Řetězec je posloupnost znaků.
Postava je prostě symbol. Například anglický jazyk má 26 znaků.
Počítače se nezabývají znaky, ale čísly (binárními). I když na obrazovce můžete vidět znaky, interně se ukládají a manipuluje se s nimi jako kombinace 0 s a 1 s.
Tato konverze znaků na číslo se nazývá kódování a obráceným procesem je dekódování. ASCII a Unicode jsou některé z populárních použitých kódování.
V Pythonu je řetězec posloupností znaků Unicode. Unicode byl zaveden, aby zahrnoval všechny znaky ve všech jazycích a přinesl jednotnost v kódování. O Unicode se můžete dozvědět z Python Unicode.
Jak vytvořit řetězec v Pythonu?
Řetězce lze vytvořit uzavřením znaků do jedné uvozovky nebo uvozovek. V Pythonu lze použít i trojité uvozovky, ale obecně se používají k reprezentaci víceřádkových řetězců a dokumentů.
# defining strings in Python # all of the following are equivalent my_string = 'Hello' print(my_string) my_string = "Hello" print(my_string) my_string = '''Hello''' print(my_string) # triple quotes string can extend multiple lines my_string = """Hello, welcome to the world of Python""" print(my_string)
Když spustíte program, výstup bude:
Ahoj Ahoj Ahoj Ahoj, vítejte ve světě Pythonu
Jak získat přístup k znakům v řetězci?
K jednotlivým znakům můžeme přistupovat pomocí indexování a k řadě znaků pomocí krájení. Index začíná od 0. Pokus o přístup k znaku mimo rozsah indexu zvýší hodnotu IndexError
. Index musí být celé číslo. Nemůžeme použít plováky ani jiné typy, výsledkem bude TypeError
.
Python umožňuje negativní indexování svých sekvencí.
Index -1
odkazuje na poslední položku, -2
na druhou poslední položku atd. K řadě položek v řetězci můžeme přistupovat pomocí operátoru krájení :
(dvojtečka).
#Accessing string characters in Python str = 'programiz' print('str = ', str) #first character print('str(0) = ', str(0)) #last character print('str(-1) = ', str(-1)) #slicing 2nd to 5th character print('str(1:5) = ', str(1:5)) #slicing 6th to 2nd last character print('str(5:-2) = ', str(5:-2))
Když spustíme výše uvedený program, získáme následující výstup:
str = programiz str (0) = p str (-1) = z str (1: 5) = rogr str (5: -2) = dop
Pokud se pokusíme získat přístup k indexu mimo rozsah nebo použít jiná čísla než celé číslo, zobrazí se chyby.
# index must be in range >>> my_string(15)… IndexError: string index out of range # index must be an integer >>> my_string(1.5)… TypeError: string indices must be integers
Krájení lze nejlépe vizualizovat zvážením indexu mezi prvky, jak je znázorněno níže.
Pokud chceme získat přístup k rozsahu, potřebujeme index, který rozdělí část z řetězce.

Jak změnit nebo odstranit řetězec?
Řetězce jsou neměnné. To znamená, že prvky řetězce nelze změnit, jakmile jsou přiřazeny. Můžeme jednoduše přiřadit různé řetězce ke stejnému jménu.
>>> my_string = 'programiz' >>> my_string(5) = 'a'… TypeError: 'str' object does not support item assignment >>> my_string = 'Python' >>> my_string 'Python'
Z řetězce nemůžeme mazat ani odstraňovat znaky. Úplné odstranění řetězce je však možné pomocí del
klíčového slova.
>>> del my_string(1)… TypeError: 'str' object doesn't support item deletion >>> del my_string >>> my_string… NameError: name 'my_string' is not defined
Řetězcové operace v Pythonu
Existuje mnoho operací, které lze provést pomocí řetězců, což z něj činí jeden z nejpoužívanějších datových typů v Pythonu.
Chcete-li se dozvědět více o datových typech dostupných v Pythonu, navštivte: Datové typy Pythonu
Zřetězení dvou nebo více řetězců
Spojení dvou nebo více řetězců do jedné se nazývá zřetězení.
+ Operátor to dělá v jazyce Python. Jednoduše psaní dvou řetězcových literálů dohromady je také zřetězí.
* Operátor může být použit k opakování řetězec pro daný počet opakování.
# Python String Operations str1 = 'Hello' str2 ='World!' # using + print('str1 + str2 = ', str1 + str2) # using * print('str1 * 3 =', str1 * 3)
Když spustíme výše uvedený program, získáme následující výstup:
str1 + str2 = HelloWorld! str1 * 3 = HelloHelloHello
Psaní dvou řetězcových literálů dohromady je také spojuje jako operátor + .
Pokud chceme zřetězit řetězce v různých řádcích, můžeme použít závorky.
>>> # two string literals together >>> 'Hello ''World!' 'Hello World!' >>> # using parentheses >>> s = ('Hello '… 'World') >>> s 'Hello World'
Iterace řetězcem
Můžeme iterovat řetězcem pomocí smyčky for. Zde je příklad, jak spočítat počet 'l v řetězci.
# Iterating through a string count = 0 for letter in 'Hello World': if(letter == 'l'): count += 1 print(count,'letters found')
Když spustíme výše uvedený program, získáme následující výstup:
Nalezena 3 písmena
Řetězcový test členství
Můžeme pomocí klíčového slova otestovat, zda v řetězci existuje podřetězec in
.
>>> 'a' in 'program' True >>> 'at' not in 'battle' False
Integrované funkce pro práci s Pythonem
Různé integrované funkce, které pracují se sekvencí, fungují také s řetězci.
Některé z běžně používaných jsou enumerate()
a len()
. enumerate()
Funkce vrací objekt vyjmenovat. Obsahuje index a hodnotu všech položek v řetězci jako páry. To může být užitečné pro iteraci.
Podobně len()
vrátí délku (počet znaků) řetězce.
str = 'cold' # enumerate() list_enumerate = list(enumerate(str)) print('list(enumerate(str) = ', list_enumerate) #character count print('len(str) = ', len(str))
Když spustíme výše uvedený program, získáme následující výstup:
list (enumerate (str) = ((0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')) len (str) = 4
Formátování řetězce v Pythonu
Sekvence útěku
If we want to print a text like He said, "What's there?", we can neither use single quotes nor double quotes. This will result in a SyntaxError
as the text itself contains both single and double quotes.
>>> print("He said, "What's there?"")… SyntaxError: invalid syntax >>> print('He said, "What's there?"')… SyntaxError: invalid syntax
One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.
An escape sequence starts with a backslash and is interpreted differently. If we use a single quote to represent a string, all the single quotes inside the string must be escaped. Similar is the case with double quotes. Here is how it can be done to represent the above text.
# using triple quotes print('''He said, "What's there?"''') # escaping single quotes print('He said, "What\'s there?"') # escaping double quotes print("He said, "What's there? "")
When we run the above program, we get the following output:
He said, "What's there?" He said, "What's there?" He said, "What's there?"
Here is a list of all the escape sequences supported by Python.
Escape Sequence | Description |
---|---|
ewline | Backslash and newline ignored |
\ | Backslash |
\' | Single quote |
" | Double quote |
a | ASCII Bell |
ASCII Backspace | |
f | ASCII Formfeed |
ASCII Linefeed | |
ASCII Carriage Return | |
ASCII Horizontal Tab | |
v | ASCII Vertical Tab |
ooo | Character with octal value ooo |
xHH | Character with hexadecimal value HH |
Here are some examples
>>> print("C:\Python32\Lib") C:Python32Lib >>> print("This is printedin two lines") This is printed in two lines >>> print("This is x48x45x58 representation") This is HEX representation
Raw String to ignore escape sequence
Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r
or R
in front of the string. This will imply that it is a raw string and any escape sequence inside it will be ignored.
>>> print("This is x61 good example") This is a good example >>> print(r"This is x61 good example") This is x61 good example
The format() Method for Formatting Strings
The format()
method that is available with the string object is very versatile and powerful in formatting strings. Format strings contain curly braces ()
as placeholders or replacement fields which get replaced.
We can use positional arguments or keyword arguments to specify the order.
# Python string format() method # default(implicit) order default_order = "(), () and ()".format('John','Bill','Sean') print('--- Default Order ---') print(default_order) # order using positional argument positional_order = "(1), (0) and (2)".format('John','Bill','Sean') print('--- Positional Order ---') print(positional_order) # order using keyword argument keyword_order = "(s), (b) and (j)".format(j='John',b='Bill',s='Sean') print('--- Keyword Order ---') print(keyword_order)
When we run the above program, we get the following output:
--- Default Order --- John, Bill and Sean --- Positional Order --- Bill, John and Sean --- Keyword Order --- Sean, Bill and John
The format()
method can have optional format specifications. They are separated from the field name using colon. For example, we can left-justify <
, right-justify >
or center ^
a string in the given space.
Můžeme také formátovat celá čísla jako binární, hexadecimální atd. A plováky lze zaokrouhlit nebo zobrazit ve formátu exponentu. Můžete použít spoustu formátování. Navštivte zde veškeré formátování řetězců dostupné u této format()
metody.
>>> # formatting integers >>> "Binary representation of (0) is (0:b)".format(12) 'Binary representation of 12 is 1100' >>> # formatting floats >>> "Exponent representation: (0:e)".format(1566.345) 'Exponent representation: 1.566345e+03' >>> # round off >>> "One third is: (0:.3f)".format(1/3) 'One third is: 0.333' >>> # string alignment >>> "|(:10)|".format('butter','bread','ham') '|butter | bread | ham|'
Formátování starého stylu
Můžeme dokonce formátovat řetězce jako starý sprintf()
styl používaný v programovacím jazyce C. %
K dosažení tohoto cíle používáme operátor.
>>> x = 12.3456789 >>> print('The value of x is %3.2f' %x) The value of x is 12.35 >>> print('The value of x is %3.4f' %x) The value of x is 12.3457
Běžné metody řetězce v Pythonu
U objektu řetězce je k dispozici řada metod. format()
Metoda, která jsme se zmínili výše, je jedním z nich. Některé z běžně používaných metod lower()
, upper()
, join()
, split()
, find()
, replace()
atd. Zde je kompletní seznam všech vestavěných metod pro práci s řetězci v Pythonu.
>>> "PrOgRaMiZ".lower() 'programiz' >>> "PrOgRaMiZ".upper() 'PROGRAMIZ' >>> "This will split all words into a list".split() ('This', 'will', 'split', 'all', 'words', 'into', 'a', 'list') >>> ' '.join(('This', 'will', 'join', 'all', 'words', 'into', 'a', 'string')) 'This will join all words into a string' >>> 'Happy New Year'.find('ew') 7 >>> 'Happy New Year'.replace('Happy','Brilliant') 'Brilliant New Year'