str Python
Introduction
A str object contains a sequence of Unicode characters (Unicode code points)
This is an immutable (Immutable) object. Read about the difference between mutable and immutable objects
here
and
here
Read about how to wrap too-long strings correctly
here
Example
>>> 'HeiHei.ru'
>>> "TopBicycle.ru"
You can use both single and double quotes. If you started with a single one you must also finish with a single one; you cannot mix them
>>> "urn.su'
File "<stdin>", line 1 "urn.su' ^ SyntaxError: EOL while scanning string literal
>>> 'urn.su"
File "<stdin>", line 1 'urn.su" ^ SyntaxError: EOL while scanning string literal
One type of quotes can be nested inside the other
>>> "Andrei's site urn.su"
"Andrei's site urn.su"
Multiline Strings
Multiline variables are often convenient for better code readability. If you enter some long value
They can be created by enclosing the value between """ and """ (or between ''' and ''')
See also
docsting
>>> """This is an example ...of a multiline ...variable of type ..str"""
'This is an example\nof a multiline\nvariable of type\nstr'
Each line break is represented by the character \n. I highlighted it in yellow for clarity. For Python it is the same kind of character as the others, just created with escaping , which we will talk about a little below.
Let us assign a value to the variable s using \n
>>> s = 'This is an example\nof a multiline\nvariable of type\nstr' >>> print(s)
This is an example of a multiline variable of type str
Exactly the same result can be obtained using """ """
>>> s = """This is an example ... of a multiline ... variable of type ... str""" >>> print(s)
This is an example of a multiline variable of type str
Universal newlines
With the Universal Newlines built into Python, \n is translated into the sequence of characters accepted in your operating system.
In
Windows
a line break (Carriage-return) is \r\n
In
Linux,
MacOS and other
UNIX
it is \r
When working with Python you do not need to think about the choice of characters for a line break; it is enough to write everywhere
\n.
The details can be studied in
PEP 278 -- Universal Newline Support
\ means the start of an escaped sequence (Escape Sequence).
I also recommend reading the article
«Wrapping a too-long line onto a new one»
Escape Sequences
An escaped character loses its original meaning and is perceived by the interpreter as an ordinary character, or on the contrary acquires an additional meaning, as we have already seen in the example \n
Compare
>>> "This is n it is a normal symbol"
'This is n it is a normal symbol'
>>> s = "This is n it is a normal symbol"
>>> print(s)
This is n it is a normal symbol
And
>>> "This is \n it is an escaped symbol"
'This is \n it is an escaped symbol'
>>> s = "This is \n it is an escaped symbol"
>>> print(s)
This is it is an escaped symbol
Instead of n there is now a line break
Escaping can be used to use the same quotes inside and outside a string
>>> "Double quote \" inside double quotes"
'Double quote " inside double quotes'
>>> 'Single quote \' inside single quotes'
'Single quote ' inside single quotes'
If escaping is not intended, \ will still be perceived by the interpreter as an attempt at escaping and will not appear as an ordinary character
>>> 'A double quote \" need not be escaped inside single quotes but \' a single one must'
'A double quote " need not be escaped inside single quotes but \' a single one must'
>>> s = 'A double quote \" need not be escaped inside single quotes but \' a single one must'
>>> print(s)
A double quote " need not be escaped inside single quotes but ' a single one must
To actually see \ you need to write \\, that is, to escape the escape character
>>> s = '\\'
>>> print(s)
\
| Escape Sequence | Value | Notes |
|---|---|---|
| \newline | Backslash and newline ignored | |
| \\ | Backslash (\) | |
| \' | Single quote (') | |
| \" | Double quote (") | |
| \a | ASCII Bell (BEL) | |
| \b | ASCII Backspace (BS) | |
| \f | ASCII Formfeed (FF) | |
| \n | ASCII Linefeed (LF) | |
| \r | ASCII Carriage Return (CR) | |
| \t | ASCII Horizontal Tab (TAB) | |
| \v | ASCII Vertical Tab (VT) | |
| \ooo | Character with octal value ooo | (1,3) |
| \xhh | Character with hex value hh | (2,3) |
| Escape Sequence | Value | Notes |
|---|---|---|
| \N{name} | Character named name in the Unicode database | (4) |
| \uxxxx | Character with 16-bit hex value xxxx | (5) |
| \Uxxxxxxxx | Character with 32-bit hex value xxxxxxxx | (6) |
| docs.python.org/3/reference/lexical_analysis.html | ||
Notes:
As in Standard C, up to three octal digits are accepted.
Unlike in Standard C, exactly two hex digits are required.
In a bytes literal, hexadecimal and octal escapes denote the byte with the given value. In a string literal, these escapes denote a Unicode character with the given value.
Changed in version 3.3: Support for name aliases 1 has been added.
Exactly four hex digits are required.
Any Unicode character can be encoded this way. Exactly eight hex digits are required.
Raw Strings
In cases when you need to use many characters that require escaping, raw strings come in handy
They allow you to enter data in an almost WYSIWYG form.
For example, it is convenient to use a raw string to store a system path address in
Windows
>>> path = r'C:\Users\Andrei\Sites\HeiHeiRu'
>>> path
'C:\\Users\\Andrei\\Sites\\HeiHeiRu'
>>> print(path)
C:\Users\Andrei\Sites\HeiHeiRu
Changing the type to str
You can turn something else into a string with the function str()
Suppose you need to combine a numeric value and a string. Although Python has dynamic typing, it will not guess for you in this case and will raise TypeError
pi = 3.1415 text = "Pi is approximately " + pi
python str_ex.py
Traceback (most recent call last): File "str_ex.py", line 3, in <module> text = "Pi is approximately " + pi TypeError: can only concatenate str (not "float") to str
If you apply str() to the variable pi the error will be fixed
pi = 3.1415 text = "Pi is approximately " + str(pi) print(text)
python str_ex.py
Pi is approximately 3.1415
Examples in interactive mode
>>> str(123)
'123'
>>> str(6.626e-34)
'6.626e-34'
Accessing string characters
If you need to use not the whole str object but only some character, it is easy to do by specifying its ordinal number in square brackets.
>>> s = "heihei.ru"
>>> s[0]
'h'
>>> s[1]
'e'
Which index must be specified to get the dot?
You can check the type of a variable with the function type()
>>> type(s)
<class 'str' >
A character that is part of a string naturally also has the type str
>>> type(s[2])
<class 'str' >
Methods (capitalize)
You can study all the methods available for working with str by calling the help function with the argument str
>>> help(str)
Let us consider the capitalize method
| capitalize(self, /) | Return a capitalized version of the string. | | More specifically, make the first character have upper case and the rest lower | case.
>>> c = "topBicycle.ru"
>>> c.capitalize()
'Topbicycle.ru'
The first letter became uppercase. All the others became lowercase.
capitalize() does not change the original string. This can be checked by running
>>> c
'topBicycle.ru'
Trimming a string
# cut x characters from the end of the string s s[:-x] # cut y characters from the start of the string s s[y:] # cut both the start and the end s[y:-x]
Example
>>> url = "https://www.heihei.ru"
>>> a = url[:-3]
>>> a
>>> 'https://www.heihei'
>>> b = a[12:]
>>> b
>>> 'heihei'
>>> c = url[12:-3]
>>> c
>>> 'heihei'
index(): the ordinal number of an element
index() returns the ordinal number of the first element that matches the given one.
index(value, start, end)
start can be omitted; by default the search goes from the start of the string
end can be omitted; by default the search goes to the end of the string
Only the index of the first a, b and c is returned
str1 = "abcabcabc" print(str1.index("a")) # 0 print(str1.index("b")) # 1 print(str1.index("c")) # 2 str2 = 'a"bc""' print(str2.index('"')) # 1
If you need to find not the first match, you can specify start
str3 = 'a"bc"def"' print(str3.index('"')) # 1 print(str3.index('"', 0)) # 1 print(str3.index('"', 1)) # 1 print(str3.index('"', 2)) # 4 print(str3.index('"', 3)) # 4 print(str3.index('"', 4)) # 4 print(str3.index('"', 5)) # 8
If you start the search from the second element, the next match will be the element with index 4. If from the fifth, then 8.
To set exact search boundaries you need both start and end
print(str3.index('"', 2, 6)) # 4 # print(str3.index('"', 5, 7)) # ValueError
If there are no matches in this range, ValueError
Unicode
Python supports Unicode because UTF-8 is used in it by default
This allows Unicode characters to be used without hassle
>>> "Pythonia voi käyttää myös vaativassa ja tieteellisessä"
'Pythonia voi käyttää myös vaativassa ja tieteellisessä'
If there were no support, most likely special characters such as umlauts would have to be replaced by their Unicode representation
>>> "Pythonia voi k\u00e4ytt\u00e4\u00e4 my\u00f6s vaativassa ja tieteellisess\u00e4"
'Pythonia voi käyttää myös vaativassa ja tieteellisessä'
Unicode characters can also be obtained in other ways
'\xe4'
'ä'
string Module
By importing the library string you can use ready-made character sets
whitespace = ' \t\n\r\v\f'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_letters = ascii_lowercase + ascii_uppercase
digits = '0123456789'
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = '01234567'
punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + ascii_letters + punctuation + whitespace
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)
The result will not be quite what you need
"b'\xd0\xb0\xd0\xb1\xd0\xb2'"
But if you add the correct encoding, абв will appear again
>>> str(b, 'utf-8')
'абв'
By specifying the wrong encoding you can get some incorrect result
>>> str(b, 'cp1251')
'абв'
By specifying the b option you can look at the contents of a file, for example an image
>>> file = "/home/andrei/image.png"
>>> f = open(file, 'rb')
>>> f.read()
b'\x89PNG\r\n…
More in the article «Working with files in Python»
split(): string to list
You can turn a string into a list with the method split()
By default the separator is a space
>>> cities = "Benalmadena Cordoba Fuengirola Malaga Narva Riga" >>> c_list = cities.split() >>> c_list[3]
'Malaga'
strip(): strip extra characters
You can remove extra characters from a string with the method strip()
By default spaces are removed
site = " heihei.ru " s = site.strip() print("of all websites", s, "is my favorite")
of all websites heihei.ru is my favorite
You can explicitly specify which characters the string should be stripped of.
capital = ",,,bbbbbcc....Riga..,,zz" c = capital.strip(",bc.z") print(c, "is the captital of Latvia")
Riga is the captital of Latvia
Self-check questions
Question: what will print(res) return
res = str3[str3.index('"')+1:str3.index('"', (str3.index('"')+1))]
Answers
res = str3[str3.index('"')+1:str3.index('"', (str3.index('"')+1))] print(res) # bc
Article author: Andrei Olegovich