Strings in programming languages are ordered sequences of characters that are used to represent any textual information. In Python, strings are a data type in their own right, so with Python’s built-in functions you can perform operations on them and format them for output.
Table of Contents
Creating
There are several ways to get a new string: with corresponding literals or by calling a ready-made function. First, let’s look at the first method, which is shown below. Here the variable string gets the value of some text, using the assignment operator. The function print will print the created string.
string = 'some text' print(string) some text
As you can see from the previous example, a string literal is surrounded by single quotes. If you want this literal to be part of a string, double quotes should be used, as shown in the following code snippet. It shows that the new string includes some ‘new’ text, which can be easily displayed.
string = "some 'new' text" print(string) some 'new' text
Sometimes you need to create objects that include several strings at once, retaining the formatting. The triple use of double quotes to select a literal solves this problem. Declaring a string this way you can give it a text with an unlimited number of paragraphs, as shown in this code
string = """some 'new' text with new line here""" print(string) some 'new' text with new line here
Special characters
Using triple quotes to format strings is not always convenient, because it sometimes takes too much space in your code. To set your own text formatting, simply use special control characters with a backslash, as shown in the following example. The tab character t is used here, as well as the line feed character n. The method print demonstrates the output of a new object on the screen.
string = "somettextnnew line here" print(string) some text new line here
The syntax characters for line formatter perform their function automatically, but sometimes it gets in the way, for example when saving a file path to disk. To disable them you need to apply special prefix r before the first quotation mark of a literal. This way the backslashes will be ignored by the program when it starts.
string = r "D:dirnew"
The following table is a list of all the Python formatting characters used in the language. As a rule, most of them allow you to change the position of the carriage to perform line feed, tabulation, or carriage return.
Symbol | Purpose |
n | Carriage advance to a new line |
b | Carriage return one character back |
f | Carriage advance to a new page |
r | Carriage return to the beginning of the line |
t | Horizontal tab |
v | Vertical tabulation |
a | Beep tone |
N | Database identifier |
u, U | 16-bit and 32-bit Unicode character |
x | 16 bit Unicode character |
o | Symbol in 8-digit number system |