Python Strings
Strings are the most commonly used data type in Python. We can create strings using quotes, either single or double.
Creating a string is simple: just assign a value to a variable. For example:
var1 = 'Hello World!'
var2 = "Python 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 substrings in Python, you can use square brackets to slice a string, as in the following example:
Example (Python 2.0+)
#!/usr/bin/python
var1
=
'
Hello World!
'
var2
=
"
Python Runoob
"
"
var1[0]:
"
,
var1
[
0
]
"
var2[1:5]:
"
,
var2
[
1
:
5
]
The example above produces:
var1[0]: H
var2[1:5]: ytho
Python string concatenation
We can slice a string and concatenate it with other strings, as in the following example:
Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
var1
=
'
Hello World!
'
"
Output :-
"
,
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 |
|---|---|
| (at the end of a line) | Line continuation character |
| \ | Backslash symbol |
| ' | Single quote |
| " | Double quote |
| \a | Bell |
| \b | Backspace |
| \e | Escape |
| \000 | null |
| \n | Newline |
| \v | Vertical tab |
| \t | Horizontal tab |
| \r | Carriage return |
| \f | Form feed |
| \oyy | Octal number, where y represents a character from 0 to 7; for example, \012 represents a newline. |
| \xyy | Hexadecimal number, starting with \x, where yy represents the character; for example, \x0a represents a newline |
| \other | Other characters are output in their normal format |
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 'HelloPython'
| | * | Repeat the string |Example (Python 2.0+)
#!/usr/bin/python
-- coding: UTF-8 --
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 execution result of the above program 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.
The following example:
#!/usr/bin/python
print "My name is %s and weight is %d kg!" % ('Zara', 21)
The example above produces the following output:
My name is Zara and weight is 21 kg!
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
In Python, triple quotes can be used to assign complex strings.
Python triple quotes allow a string to span multiple lines, and the string can contain newlines, tabs, and other special characters.
The syntax of triple quotes is a pair of consecutive single or double quotes (usually used in pairs).
>>> hi = '''hi
there'''
>>> hi # repr()
'hi\nthere'
>>> print hi # str()
hi
there
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; marking it with triple quotes is much easier, whereas using the traditional escape-character system would be very tedious.
errHTML = '''
Friends CGI Demo
ERROR
%s
'''
cursor.execute('''
CREATE TABLE users (
login VARCHAR(8),
uid INTEGER,
prid INTEGER)
''')
Unicode strings
Defining a Unicode string in Python is as simple as defining a normal string:
>>> u'Hello World !'
u'Hello World !'
A lowercase u before the quotes indicates that a Unicode string is being created here. If you want to add a special character, you can use Python's Unicode-Escape encoding. As shown in the following example:
>>> u'Hello\u0020World !'
u'Hello World !'
The \u0020 marker to be replaced indicates that a Unicode character with code value 0x0020 (the space character) is inserted at the given position.
Python string built-in functions
String methods were gradually added from Python 1.6 to 2.0 - they were also added to Jython.
These methods implement most of the methods of the string module. The table below lists the methods currently supported by strings; all of them include Unicode support, and some are even specifically for Unicode.
| Method | Description |
|---|---|
|
Capitalize the first character of the string |
|
|
Return a new string with the original string centered and padded with spaces to length width |
|
|
Return the number of times str appears in string; if beg or end is specified, return the number of times str appears within the specified range |
|
|
Decode string using the encoding specified by encoding; on error, a ValueError exception is raised by default, unless errors is specified as 'ignore' or 'replace' |
|
|
Encode string using the encoding specified by encoding; on error, a ValueError exception is raised by default, unless errors is specified as 'ignore' or 'replace' |
|
|
Check whether the string ends with obj; if beg or end is specified, check whether it ends with obj within the specified range. Return True if so, False otherwise. |
|
|
Convert tab characters in the string to spaces; the default number of spaces for a tab is 8. |
|
|
Check whether str is contained in string; if beg and end specify a range, check whether it is contained within that range. Return the starting index if so, otherwise return -1 |
|
|
Format a string |
|
|
Same as the find() method, except that an exception is raised if str is not in string. |
|
|
If string has at least one character and all characters are letters or digits, return True, otherwise return False |
|
|
If string has at least one character and all characters are letters, return True, otherwise return False |
|
|
If string contains only decimal digits, return True; otherwise return False. |
|
|
If string contains only digits, return True; otherwise return False. |
|
|
If string contains at least one case-sensitive character and all such (case-sensitive) characters are lowercase, return True; otherwise return False |
|
|
If string contains only digit characters, return True; otherwise return False |
|
|
If string contains only whitespace, return True; otherwise return False. |
|
|
If string is titlecased (see title()), return True; otherwise return False |
|
|
If string contains at least one case-sensitive character and all such (case-sensitive) characters are uppercase, return True; otherwise return False |
|
|
Using string as the separator, merge all elements of seq (their string representations) into a new string |
|
|
Return a new string with the original string left-aligned and padded with spaces to length width |
|
|
Convert all uppercase characters in string to lowercase. |
|
|
Strip the leading spaces from string |
|
|
The maketrans() method creates 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. |
|
|
Return the string str the largest letter in it. |
|
|
Return the string str the smallest letter in it. |
|
|
Somewhat like a combination of find() and split(), starting from the first position where str appears, it splits the string into a 3-element tuple (string_pre_str, str, string_post_str); if string does not contain str, then string_pre_str == string. |
|
|
Replace str1 in string with str2; if num is specified, replace no more than num times. |
|
|
Similar to the find() function, return the position of the last occurrence of the string; if there is no match, return -1. |
|
|
Similar to index(), but return the index of the last matched substring. |
|
|
Return a new string with the original string right-aligned and padded with spaces to length width |
|
|
Similar to the partition() function, but searching from the right |
|
|
Remove the trailing spaces from string. |
|
|
Slice string using str as the separator; if num is specified, split only num+1 substrings |
|
|
Split by line ('\r', '\r\n', '\n'), returning a list with each line as an element. If the parameter keepends is False, line breaks are not included; if True, line breaks are retained. |
|
|
Check whether the string starts with obj; return True if so, False otherwise. If beg and end are specified, check within the specified range. |
|
|
Perform lstrip() and rstrip() on string |
|
|
Swap the case of characters in string |
|
|
Return a titlecased version of string, meaning all words start with an uppercase letter and the remaining letters are lowercase (see istitle()) |
|
|
Convert the characters in string according to the table given by str (containing 256 characters), put the characters to be filtered out in the del parameter |
|
|
Convert lowercase letters in string to uppercase |
|
|
Return a string of length width, with the original string right-aligned and padded with 0 in front |