str Python
Introduction
An object of type str contains a sequence of Unicode characters (Unicode code points)
It is an immutable object. That is, once it has been created you can no longer change anything in it.
Example
>>> 'HeiHei.ru'
>>> "TopBicycle.ru"
You can use both single and double quotes. If you started with a single one, you have to finish with a single one too - you cannot mix them
>>> "eth1.ru'
File "<stdin>", line 1 "eth1.ru' ^ SyntaxError: EOL while scanning string literal
>>> 'eth1.ru"
File "<stdin>", line 1 'eth1.ru" ^ SyntaxError: EOL while scanning string literal
One type of quotes can be nested inside the other
>>> "Andrei's site eth1.ru"
"Andrei's site eth1.ru"
Multiline Strings
Multiline variables are often convenient for better code readability. If you are entering some long value
You can create them 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 character as all the others, just created with the help of escaping , which we will talk about a little further below.
Let us assign the variable s a value 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 newline
With the help of Universal Newlines built into Python, \n is translated into the sequence of characters that is 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
\n.
You can study the details in
PEP 278 -- Universal Newline Support
\ marks the beginning of an escape 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 it acquires an additional meaning, as we have already seen in the
example of \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 applied 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 \" does not need escaping inside single quotes but a \' single one does'
'A double quote " does not need escaping inside single quotes but a \' single one does'
>>> s = 'A double quote \" does not need escaping inside single quotes but a \' single one does'
>>> print(s)
A double quote " does not need escaping inside single quotes but a ' single one does
To actually see the \ you need to write \\, that is, 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 where you need to use many characters that require escaping, raw strings come in handy
They let you enter data in a practically
WYSIWYG
form.
For example, it is convenient to use a raw string to store the address of a system path in
Windows
>>> path = r'C:\Users\Andrei\Sites\HeiHeiRu'
>>> path
'C:\\Users\\Andrei\\Sites\\HeiHeiRu'
>>> print(path)
C:\Users\Andrei\Sites\HeiHeiRu
Change the type to str
With the str() function you can change the type of an object to a string. Usually this is used with numbers
>>> str(123)
'123'
>>> str(6.626e-34)
'6.626e-34'
Accessing string characters
If you need to use not the whole object of type str but only some character, this is easy to do by specifying its ordinal number in square brackets.
>>> s = "heihei.ru"
>>> s[0]
'h'
>>> s[1]
'e'
Which index do you need to specify to get the dot?
You can check the type of a variable with the help of 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 str argument
>>> help(str)
Let us look at 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 rest became lowercase.
capitalize() does not change the original string. You can verify this by running
>>> c
'topBicycle.ru'
Trimming a string
# cut off x characters from the end of string s
s[:-x]
# cut off y characters from the beginning of string s
s[y:]
# trim both the beginning 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'
Unicode
Python supports Unicode because UTF-8 is used in it by default
This lets you use Unicode characters without any hassle
>>> "Pythonia voi käyttää myös vaativassa ja tieteellisessä"
'Pythonia voi käyttää myös vaativassa ja tieteellisessä'
If there were no support, you would most likely have to replace special characters such as umlauts with their Unicode representation
>>> "Pythonia voi k\u00e4ytt\u00e4\u00e4 my\u00f6s vaativassa ja tieteellisess\u00e4"
'Pythonia voi käyttää myös vaativassa ja tieteellisessä'
You can also get Unicode characters in other ways
'\xe4'
'ä'
string Module
By importing the library strig you can use ready-made sets of characters
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, the абв characters will appear again
>>> str(b, 'utf-8')
'абв'
By specifying the wrong encoding you can get some kind of 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 details in the article «Working with files in Python»
Article author: Andrei Olegovich