Python strings
Python strings are the most commonly used data types. We can use quotation marks ( 'or ") to create a string.
Create a string is very simple, as long as the variable is assigned a value. E.g:
var1 = 'Hello World!' var2 = "Python w3big"
Python access string value
Python does not support single character type, a single character is also used as a Python strings.
Python access substring, you can use square brackets to intercept string following examples:
#!/usr/bin/python var1 = 'Hello World!' var2 = "Python w3big" print "var1[0]: ", var1[0] print "var2[1:5]: ", var2[1:5]
The results of the above examples:
var1[0]: H var2[1:5]: ytho
Python string Update
You can modify an existing string, and assign them to another variable, the following examples:
#!/usr/bin/python # -*- coding: UTF-8 -*- var1 = 'Hello World!' print "更新字符串 :- ", var1[:6] + 'w3big!'
Examples of the results of the above
更新字符串 :- Hello w3big!
Python escape character
When you need to use special characters in the character, python with a backslash (\) escape character. In the following table:
Escape character | description |
---|---|
\ (At the end of the line) | ULink |
\\ | Backslash |
\ ' | apostrophe |
\ " | Double quotes |
\ A | Bell |
\ B | Backspace (Backspace) |
\ E | Escape |
\ 000 | air |
\ N | Wrap |
\ V | Vertical tab |
\ T | Horizontal tab |
\ R | Enter |
\ F | PAGE |
\ Oyy | Character octal, yy representatives, for example: \ o12 represent the newline |
\ Xyy | Character hexadecimal number, yy representatives, for example: \ x0a represent the newline |
\ Other | Other character output in a common format |
Python string operators
The following table instance variable is a string "Hello", b variable value "Python":
Operators | description | Examples |
---|---|---|
+ | String concatenation | a + b output: HelloPython |
* | Repeat output string | a * 2 output: HelloHello |
[] | Gets characters in the string by index | a [1] outpute |
[:] | Interception of the string part | a [1: 4] outputell |
in | Member operator - If the string contains the given character returns True | H in a 1 output |
not in | Member operator - If the string does not contain a given character returns True | M not in a 1 output |
r / R | The original string - the original string: all strings are directly used in accordance with the literal meaning, there is no escaping special characters or not print. In addition to the original string before the first quote with the letter "r" (may be the case) than with ordinary string has an almost identical syntax. | print r '\ n' output \ n and print R '\ n'output \ n |
% | Format string | See the next section |
Examples are as follows:
#!/usr/bin/python # -*- coding: UTF-8 -*- a = "Hello" b = "Python" print "a + b 输出结果:", a + b print "a * 2 输出结果:", a * 2 print "a[1] 输出结果:", a[1] print "a[1:4] 输出结果:", a[1:4] if( "H" in a) : print "H 在变量 a 中" else : print "H 不在变量 a 中" if( "M" not in a) : print "M 不在变量 a 中" else : print "M 在变量 a 中" print r'\n' print R'\n'
The above program execution results:
a + b 输出结果: HelloPython a * 2 输出结果: HelloHello a[1] 输出结果: e a[1:4] 输出结果: ell H 在变量 a 中 M 不在变量 a 中 \n \n
Python string formatting
Python supports output formatted strings. Although this can include very complicated expressions, the most basic usage is to insert a value into a string string specifier% s in.
In Python, and C string formatted using the same syntax as the sprintf function.
The following examples:
#!/usr/bin/python print "My name is %s and weight is %d kg!" % ('Zara', 21)
Examples of the above output:
My name is Zara and weight is 21 kg!
python string formatting symbols:
Symbol | description |
---|---|
% c | Formatting characters and their ASCII code |
% s | Format string |
% d | Integer format |
% u | Unsigned int format |
% o | Formatting unsigned octal |
% x | Unsigned hexadecimal format |
% X | Unsigned hexadecimal format (uppercase) |
% f | Format floating-point numbers, the accuracy can be specified after the decimal point |
% e | Scientific notation floating point format |
% E | Action with% e, using scientific notation floating point format |
% g | % f and% e shorthand |
% G | % f% E and shorthand |
% p | Hexadecimal address format number of variables |
Formatting operator assisted instruction:
symbol | Features |
---|---|
* | Define the width or decimal precision |
- | Alignment of the left do |
+ | Positive numbers displayed on the front plus sign (+) |
<Sp> | Display space before positive numbers |
# | Show zero in front of the octal number ( '0'), in front of the hexadecimal display '0x' or '0X' (depending on the use the 'x' or 'X') |
0 | The figures show the front fill '0' instead of the default spaces |
% | '%%' Outputs a single '%' |
(Var) | Variable mapping (dictionary parameter) |
mn | m is the minimum overall width of the display, n is the number of decimal places (if available) |
Python triple quotes (triple quotes)
Three python quotes can be complex string copying:
python triple quotes allow a string across multiple lines, the string can contain line breaks, tabs, and other special characters.
Triple quotes syntax is a pair of continuous single or double quotes (usually paired with).
>>> hi = '''hi there''' >>> hi # repr() 'hi\nthere' >>> print hi # str() hi there
Triple quotes allow programmers from the quagmire inside quotes and special strings start to finish to maintain a small format string is called WYSIWYG (WYSIWYG) format.
A typical use case is when you need an HTML or SQL, then use a combination of string, escaping special string will be very tedious.
errHTML = ''' <HTML><HEAD><TITLE> Friends CGI Demo</TITLE></HEAD> <BODY><H3>ERROR</H3> <B>%s</B><P> <FORM><INPUT TYPE=button VALUE=Back ONCLICK="window.history.back()"></FORM> </BODY></HTML> ''' cursor.execute(''' CREATE TABLE users ( login VARCHAR(8), uid INTEGER, prid INTEGER) ''')
Unicode strings
Python is a string of Unicode and normal strings as simple as:
>>> u'Hello World !' u'Hello World !'
Quotes before lowercase "u" indicates created here is a Unicode string. If you want to add a special character, you can use the Python Unicode-Escape encoding. In the following example:
>>> u'Hello\u0020World !' u'Hello World !'
Replaced \ u0020 identity expressed in a given position to insert Unicode character encoding value 0x0020 (the space character).
python string built-in functions
Python1.6 string method is from 2.0 to slowly add to the mix - they are also added to the Jython.
These methods achieve the majority method string module, the following table lists the built-in support of the current string method, all methods includes support for Unicode, some even specifically for Unicode.
method | description |
---|---|
The first character uppercase | |
Returns a string of the original center, and padded with spaces to the length of the width of the new string | |
string.count (str, beg = 0, end = len (string)) | Returns the number of times the string str appears inside, str occur if the beg or end specified is returned within the specified range |
string.decode (encoding = 'UTF-8 ', errors = 'strict') | Encoding to specified encoding format decoding string, the default error message if a ValueError exception, unless the errors specified is 'ignore' or 'replace' |
string.encode (encoding = 'UTF-8 ', errors = 'strict') | In encoding the specified encoding format string, the default error message if a ValueError exception, unless the errors specified is 'ignore' or 'replace' |
string.endswith (obj, beg = 0, end = len (string)) | Check whether the string obj end, if specified beg or end within the specified range is checked whether obj end, and if so, returns True, otherwise False. |
String string in tab symbol into space, tab symbols for the default number of spaces is 8. | |
string.find (str, beg = 0, end = len (string)) | Detection is included in the string str, if you beg and end the specified range, it is checked whether contained within the specified range, if it is the beginning of the index value is returned, otherwise -1 |
string.index (str, beg = 0, end = len (string)) | With the find () method of the same, but if the string str is not an exception will be reported. |
If there is at least one character string and all the characters are the letters or numbers you back Return True, otherwise False | |
If there is at least one character string and all the characters are letters it returns True, Otherwise, it returns False | |
If the string contains only decimal digits returns True otherwise False. | |
If the string contains only digit returns True otherwise False. | |
If the string contains at least one case-sensitive characters, and all of these (case-sensitive) characters are lowercase, returns True, otherwise False | |
If the string contains only numeric characters, it returns True, otherwise False | |
If the string contains only spaces, returns True, otherwise False. | |
If the string is the title (see title ()) returns True, otherwise False | |
If the string contains at least one case-sensitive characters, and all of these (case-sensitive) characters are uppercase, it returns True, otherwise False | |
In string as a delimiter, will seq all elements (string representation) into a new string | |
Returns a string of former left-justified, and padded with spaces to the length of the width of the new string | |
String in all uppercase characters converted to lowercase. | |
Truncated string left spaces | |
maketrans () method is used to create character mappings conversion table, for taking two parameters, the easiest way is called, the first argument is a string that represents the character to be converted, the second parameter is the string representation of goal conversions . | |
Returns the string str largest letters. | |
Returns the string str smallest letters. | |
A bit like find () and split () combination, the first position since emerging from str, string string into a 3-element tuple (string_pre_str, str, string_post_str), if not contained in string str the string_pre_str == string. | |
string.replace (str1, str2, num = string.count (str1)) | Replace the string in str1 into str2, if num specified, replace no more than num times. |
string.rfind (str, beg = 0, end = len (string)) | Similar to the find () function, but start looking from the right. |
string.rindex (str, beg = 0, end = len (string)) | Similar to the index (), but starting from the right. |
Returns a string of former right-aligned and padded with spaces to the new string of length width | |
string.rpartition (str) | Similar to the partition () function, but start looking from the right. |
Remove the space string end of the string. | |
string.split (str = "", num = string.count (str)) | Takes str separator slice string, if num value is specified, then only substrings separated num |
Separated by rows, each row is returned as an element of a list that contains only the sections specified if num num rows. | |
string.startswith (obj, beg = 0, end = len (string)) | Check whether a string begins with obj, it returns True, otherwise False. If beg and end the specified value, check within the specified range. |
Executive lstrip in string () and rstrip () | |
Flip string in case | |
Back "title" of the string, that is the beginning of all words are capitalized, remaining letters lowercase (see istitle ()) | |
Table str given (256 characters) to convert the character string, To filter out the character into del argument | |
Conversion string of lowercase letters to uppercase | |
Returns a string of length width, the original string string right justified, padded with zeros in front | |
isdecimal () method checks whether the string contains only decimal characters. This method exists only in unicode object. |