Python3 Strings
Strings are the most commonly used data type in Python. We can create a string using quotes ( ' or " ).
Creating a string is simple: just assign a value to a variable. For example:
var1
=
'
Hello World!
'
var2
=
"
Runoob
"
Accessing values in a Python string
Python does not support a single-character type; a single character is also treated as a string in Python.
To access a substring in Python, use square brackets [] to slice the string; the syntax for slicing is as follows:
变量[头下标:尾下标]
Index values start at 0 as the starting value,-1 as the starting position from the end.

The following example:
Example (Python 3.0+)
#!/usr/bin/python3
var1
=
'
Hello World!
'
var2
=
"
Runoob
"
(
"
var1[0]:
"
,
var1
[
0
]
)
(
"
var2[1:5]:
"
,
var2
[
1
:
5
]
)
The example above produces:
var1[0]: H
var2[1:5]: unoo
Updating Python strings
You can take part of a string and concatenate it with other fields, as in the following example:
Example (Python 3.0+)
#!/usr/bin/python3
var1
=
'
Hello World!
'
(
"
Updated string :
"
,
var1
[
:
6
]
'
Runoob!
'
)
Result of the above example
已更新字符串 : Hello Runoob!
Python escape characters
When special characters are needed inside a character string, Python uses the backslash as an escape character, as shown in the table below:
| Escape character | Description | Example |
|---|---|---|
| (at the end of a line) | Line continuation character |
>>> print("line1
... line2
... line3") line1 line2 line3 >>> | | backslash | Backslash symbol |
>>> print("\")
|
| ' | Single quote | >>> print(''')
'
|
| " | Double quote | >>> print(""")
" |
| \a | Bell | >>> print("\a") The computer beeps after execution. |
| \b | Backspace | >>> print("Hello \b World!")
Hello World! |
| \000 | Null | >>> print("\000")
>>>
|
| \n | Line feed | >>> print("\n")
>>>
|
| \v | Vertical tab | >>> print("Hello \v World!")
Hello
World!
>>> |
| \t | Horizontal tab | >>> print("Hello \t World!")
Hello World!
>>> |
| \r | Carriage return: moves the content after CR to the start of the string and replaces the leading characters one by one until the content after CR has completely replaced them. | >>> print("Hello\rWorld!")
World!
>>> print('google runoob taobao\r123456')
123456 runoob taobao
|
| \f | Form feed | >>> print("Hello \f World!")
Hello
World!
>>>
|
| \yyy | Octal number; y stands for characters 0-7, for example \012 stands for line feed. | >>> print("\110\145\154\154\157\40\127\157\162\154\144\41")
Hello World! |
| \xyy | Hexadecimal number, starting with the \x prefix; y represents the character, for example \x0a stands for line feed | >>> print("\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x21")
Hello World! |
| \other | Other characters are output in the normal format | |
Use the carriage return character to implement a percentage progress display:
Example
import
time
for
i
in
range
(
101
)
:
Add a progress bar graphic and a percentage
bar
=
'['
'='
(
i //
2
)
' '
(
50
- i //
2
)
']'
(
f
"\r{bar} {i:3}%"
,
end
=
''
,
flush
=
True
)
time
.
sleep
(
0.05
)
(
)
In the following example we use different escape characters to demonstrate single quotes, newlines, tabs, backspaces, form feeds, ASCII, binary, octal and hexadecimal numbers:
Example
(
''Hello, world!''
)
Output: 'Hello, world!'
(
"Hello, world!\nHow are you?"
)
Output: Hello, world!
How are you?
(
"Hello, world!\tHow are you?"
)
Output: Hello, world! How are you?
(
"Hello,\b world!"
)
Output: Hello world!
(
"Hello,\f world!"
)
Output:
Hello,
world!
(
"The ASCII value of A is:"
,
ord
(
'A'
)
)
Output: The ASCII value of A is: 65
(
"The hexadecimal escape sequence for the ASCII code of A"
)
Output: A is the ASCII code of A
decimal_number
=
42
binary_number
=
bin
(
decimal_number
)
Convert decimal to binary
(
'Converted to binary:'
,
binary_number
)
Convert to binary: 0b101010
octal_number
=
oct
(
decimal_number
)
Convert decimal to octal
(
'Converted to octal:'
,
octal_number
)
Convert to octal: 0o52
hexadecimal_number
=
hex
(
decimal_number
)
Convert decimal to hexadecimal
(
'Converted to hexadecimal:'
,
hexadecimal_number
)
Convert to hexadecimal: 0x2a
Python string operators
In the table below, variable a has the string value "Hello" and b has the value "Python":
| Operator | Description | Example |
|---|---|---|
| + | String concatenation | a + b output: HelloPython |
| * | Repeat the output string | a*2 output: HelloHello |
| [] | Get a character in the string by index | a[1] output e |
| [ : ] | Take part of a string, following theleft-closed, right-openrule; str[0:2] does not include the 3rd character. | a[1:4] output ell |
| in | Membership operator - returns True if the string contains the given character | 'H' in a Output True |
| not in | Membership operator - returns True if the string does not contain the given character | 'M' not in a Output True |
| r/R | Raw strings - in a raw string all strings are used exactly as written literally, with no escaping of special or unprintable characters. Apart from prefixing the first quote with the letter r (uppercase or lowercase), a raw string has almost exactly the same syntax as a normal string. |
print( r'\n' ) print( R'\n' )
| | % | Format string | See the next section. |Example (Python 3.0+)
#!/usr/bin/python3
a
=
"
Hello
"
b
=
"
Python
"
(
"
a + b output:
"
,
a
b
)
(
"
a * 2 output:
"
,
a
2
)
(
"
a[1] output:
"
,
a
[
1
]
)
(
"
a[1:4] output:
"
,
a
[
1
:
4
]
)
if
(
"
H
"
in
a
)
:
(
"
H is in variable a
"
)
else
:
(
"
H is not in variable a
"
)
if
(
"
M
"
not
in
a
)
:
(
"
M is not in variable a
"
)
else
:
(
"
M is in variable a
"
)
(
r
'
\n
'
)
(
R
'
\n
'
)
The output of the above example is:
a + b 输出结果: HelloPython
a * 2 输出结果: HelloHello
a[1] 输出结果: e
a[1:4] 输出结果: ell
H 在变量 a 中
M 不在变量 a 中
\n
\n
Python string formatting
Python supports formatted string output. Although this can involve very complex expressions, the most basic usage is to insert a value into a string containing the %s format specifier.
In Python, string formatting uses the same syntax as the sprintf function in C.
Example (Python 3.0+)
#!/usr/bin/python3
(
"
My name is %s and I am %d years old!
"
%
(
'
Xiao Ming
'
,
10
)
)
The example above produces the following output:
我叫 小明 今年 10 岁!
Python string formatting symbols:
| Symbol | Description |
|---|---|
| %c | Format a character and its ASCII code |
| %s | Format a string |
| %d | Format an integer |
| %u | Format an unsigned integer |
| %o | Format an unsigned octal number |
| %x | Format an unsigned hexadecimal number |
| %X | Format an unsigned hexadecimal number (uppercase) |
| %f | Format a floating-point number, with a specified precision after the decimal point |
| %e | Format a floating-point number in scientific notation |
| %E | Same as %e, format a floating-point number in scientific notation |
| %g | Shorthand for %f and %e |
| %G | Shorthand for %f and %E |
| %p | Format the address of a variable in hexadecimal |
Formatting operator auxiliary directives:
| sign before positive numbers | Function |
|---|---|
| * | Define the width or decimal precision |
| - | Use for left alignment |
| + | Display a plus sign ( + ) in front of positive numbers |
| Display a space in front of positive numbers | |
| # | Display a zero ('0') in front of octal numbers, and '0x' or '0X' in front of hexadecimal numbers (depending on whether 'x' or 'X' is used) |
| 0 | Pad the displayed number with '0' instead of the default space |
| % | '%%' outputs a single '%' |
| (var) | Map variables (dictionary arguments) |
| m.n. | m is the minimum total display width, n is the number of digits after the decimal point (if applicable) |
Starting with Python 2.6, a new string formatting function was added str.format(), which enhances the string formatting capabilities.
Python triple quotes
Python triple quotes allow a string to span multiple lines and can contain newlines, tabs and other special characters. An example follows
Example (Python 3.0+)
#!/usr/bin/python3
para_str
=
"""
This is an example of a multi-line string. Multi-line strings can use the TAB character (
\t
). You can also use the newline character [
\n
]。
"""
(
para_str
)
The example above produces:
这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( )。
也可以使用换行符 [
]。
Triple quotes free programmers from the quagmire of quotes and special strings, keeping a small block of string formatting in what is called WYSIWYG (what you see is what you get) form from beginning to end.
A typical use case is when you need a block of HTML or SQL; building it by combining strings would make escaping special strings very tedious.
errHTML
=
'''
ERROR
%s'''
cursor
.
execute
(
'''
CREATE TABLE users ( login VARCHAR(8), uid INTEGER, prid INTEGER)
'''
)
f-string
f-string was added in Python 3.6 and later; it is called a literal formatted string and is a new syntax for formatting strings.
Previously we were used to using the percent sign (%):
Example
name
=
'Runoob'
'Hello %s'
% name
'Hello Runoob'
f-string A formatted string starts with f followed by the string; expressions inside the string are wrapped in braces {} and are replaced by the computed value of the variable or expression, as shown below:
Example
name
=
'Runoob'
f
'Hello {name}'
Replace variables
'Hello Runoob'
f
'{1+2}'
Use expressions
'3'
w
=
{
'name'
:
'Runoob'
,
'url'
:
'www.runoob.com'
}
f
'{w["name"]}: {w["url"]}'
'Runoob: www.runoob.com'
This approach is clearly much simpler; there is no need to decide whether to use %s or %d.
In Python 3.8 you can use the = sign to join an expression with its result:
Example
x
=
1
(
f
'{x+1}'
)
Python 3.6
2
x
=
1
(
f
'{x+1=}'
)
Python 3.8
x+
1
=
2
Unicode strings
In Python 2, ordinary strings were stored as 8-bit ASCII, while Unicode strings were stored as 16-bit Unicode strings, which could represent a larger character set. The syntax was to add the prefix u。
In Python 3, all strings are Unicode strings.
Python string built-in functions
The commonly used built-in functions for Python strings are as follows:
| No. | Method and description |
|---|---|
| 1 |
Convert the first character of the string to uppercase | | 2 | Return a string centered in a specified width; fillchar is the fill character and defaults to a space. | | 3 |
count(str, beg= 0,end=len(string))
Return the number of times str occurs in string, or within the specified range if beg or end is given | | 4 |bytes.decode(encoding="utf-8", errors="strict")
Python3 has no decode method, but we can use the decode() method of a bytes object to decode a given bytes object, which can be produced by str.encode(). | | 5 |encode(encoding='UTF-8',errors='strict')
Encode the string using the encoding specified by encoding; on error a ValueError is raised by default unless errors is set to 'ignore' or 'replace' | | 6 |endswith(suffix, beg=0, end=len(string))
Check whether the string ends with suffix, or within the specified range if beg or end is given; returns True if so, otherwise False.
find(str, beg=0, end=len(string))
Check whether str is contained in the string, or within the specified range if beg and end are given; returns the starting index if found, otherwise -1 | | 9 |index(str, beg=0, end=len(string))
Same as the find() method, except that an exception is raised if str is not in the string. | | 10 | Check whether a string consists of letters and digits, that is, all characters are letters or digits. Returns True if the string has at least one character and all characters are letters or digits; otherwise False. | | 11 | Returns True if the string has at least one character and all characters are letters or Chinese characters, otherwise False | | 12 | Returns True if the string contains only digits, otherwise False.. | | 13 | Returns True if the string contains at least one cased character and all such cased characters are lowercase, otherwise False | | 14 | Returns True if the string contains only numeric characters, otherwise False | | 15 | Returns True if the string contains only whitespace, otherwise False. | | 16 | Returns True if the string is titlecased (see title()), otherwise False | | 17 | Returns True if the string contains at least one cased character and all such cased characters are uppercase, otherwise False | | 18 | Use the specified string as a separator to merge all elements of seq (their string representations) into a new string | | 19 | Return the length of the string | | 20 | Return a new string with the original string left-aligned and padded with fillchar to length width; fillchar defaults to a space. | | 21 | Convert all uppercase characters in the string to lowercase. | | 22 | Remove spaces or specified characters from the left side of the string. | | 23 | Create a character mapping translation table. In the simplest call, which takes two arguments, the first argument is a string containing the characters to be translated and the second is a string containing the translation targets. | | 24 | Return the largest letter in the string str. | | 25 | Return the smallest letter in the string str. | | 26 | Replace old with new in the string; if max is specified, no more than max replacements are made. | | 27 |rfind(str, beg=0,end=len(string))
Similar to the find() function, but searching starts from the right. | | 28 |rindex( str, beg=0, end=len(string))
Similar to index(), but starting from the right. | | 29 | Return a new string with the original string right-aligned and padded with fillchar (defaults to a space) to length width | | 30 | Remove spaces or specified characters from the end of the string. | | 31 |split(str="", num=string.count(str))
Slice the string using str as the delimiter; if num has a specified value, only num+1 substrings are taken | | 32 | Split at line boundaries (carriage return, carriage return plus newline, or newline) and return a list with each line as an element. If keepends is False, line breaks are not included; if True, they are kept. | | 33 |startswith(substr, beg=0,end=len(string))
Check whether the string starts with the specified substring substr, returning True if so and False otherwise. If beg and end are specified, the check is performed within that range. | | 34 | Perform lstrip() and rstrip() on the string | | 35 | Convert uppercase to lowercase and lowercase to uppercase in the string | | 36 | Return a "titlecased" string, that is, all words begin with an uppercase letter and the remaining letters are lowercase (see istitle()) | | 37 | Convert the characters of string according to the table given by table (containing 256 characters); the characters to be filtered out go in the deletechars parameter | | 38 | Convert lowercase letters in the string to uppercase | | 39 | Return a string of length width with the original string right-aligned and padded with leading zeros | | 40 | Check whether the string contains only decimal characters; returns true if so, otherwise false. |