1. String definition
String is the most commonly used data type in Python. We can use quotation marks ('or ') to create strings.
Creating a string is as simple as assigning a value to a variable. For example:
var1 = 'Hello World!' var2 = "Python Runoob"
2. Access the value in the string
Python does not support single character type, which is also used as a string in Python.
When Python accesses a substring, you can use square brackets to intercept the string, as shown in the following example:
var1 = 'Hello World!' var2 = "Python Runoob" print "var1[0]: ", var1[0] #Result: H print "var2[1:5]: ", var2[1:5] #Result: ytho #Bracket left closed right open
3. String connection
We can intercept strings and connect them with other strings, as shown in the following example:
var1 = "hello world" print(var1[:6] + "dashuaibi!") #[: 6] represents 0-5 for intercepting var string # result hello dashuaibi!
4. Escape character
python uses backslashes \ to escape characters when special characters need to be used in characters. The following table:
Escape character | describe |
---|---|
(at the end of the line) | Continuation character |
\ | Backslash symbol |
' | Single quotation mark |
" | Double quotation mark |
\a | Ring the bell |
\b | Backspace |
\e | Escape |
\000 | empty |
\n | Line feed |
\v | Vertical tab |
\t | horizontal tab |
\r | enter |
\f | Page change |
\oyy | Octal number, y represents characters from 0 to 7, for example: \ 012 represents line feed. |
\xyy | Hexadecimal number, starting with \ x, yy represents characters, for example: \ x0a represents line feed |
\other | Other characters are output in normal format |
5. String operator
In the following table, the value of instance variable a is the string "Hello", and the value of b variable is "Python":
Operator | describe | example |
---|---|---|
+ | String connection | >>>a + b 'HelloPython' |
* | Duplicate output string | >>>a * 2 'HelloHello' |
[] | Get characters in string by index | >>>a[1] 'e' |
[ : ] | Intercepts a portion of a string | >>>a[1:4] 'ell' |
in | Member operator - returns True if the string contains the given character | >>>"H" in a True |
not in | Member operator - returns True if the string does not contain the given character | >>>"M" not in a True |
r/R | Original string - original string: all strings are used directly according to the literal meaning. There are no special escape characters or characters that cannot be printed. The original string has almost the same syntax as an ordinary string except that the letter "r" (case sensitive) is added before the first quotation mark of the string. | >>>print r'\n' \n >>> print R'\n' \n |
% | Format string | See the next chapter |
a = "Hello" b = "Python" print "a + b Output results:", a + b print "a * 2 Output results:", a * 2 print "a[1] Output results:", a[1] print "a[1:4] Output results:", a[1:4] if( "H" in a) : print "H In variable a in" else : print "H Not in variable a in" if( "M" not in a) : print "M Not in variable a in" else : print "M In variable a in" print r'\n' print R'\n' #result a + b Output results: HelloPython a * 2 Output results: HelloHello a[1] Output results: e a[1:4] Output results: ell H In variable a in M Not in variable a in \n \n
6. String formatting
Python supports the output of formatted strings. Although this may use very complex expressions, the most basic usage is to insert a value into a string with the string formatter% s.
In Python, string formatting uses the same syntax as the sprintf function in C.
Examples are as follows:
print "My name is %s and weight is %d kg!" % ('Zara', 21) #result My name is Zara and weight is 21 kg!
python string formatting symbol:
Symbol | describe |
---|---|
%c | Formatted characters and their ASCII codes |
%s | format string |
%d | Format integer |
%u | Format unsigned integer |
%o | Format unsigned octal number |
%x | Format unsigned hexadecimal number |
%X | Format unsigned hexadecimal number (upper case) |
%f | Format floating-point numbers to specify the precision after the decimal point |
%e | Formatting floating point numbers with scientific counting |
%E | The function is the same as%e, format floating-point numbers with scientific counting method |
%g | %Abbreviations for f and% e |
%G | %Abbreviations for F and% E |
%p | Format the address of a variable with a hexadecimal number |
Format operator helper:
Symbol | function |
---|---|
* | Define width or decimal precision |
- | Align left with |
+ | Displays a plus sign (+) before a positive number |
Show spaces before positive numbers | |
# | Zero ('0 ') is displayed in front of octal numbers and' 0x 'or' 0x 'is displayed in front of hexadecimal numbers (depending on whether' x 'or' x 'is used) |
0 | The displayed number is preceded by '0' instead of the default space |
% | '%%' output a single '%' |
(var) | Mapping variables (Dictionary parameters) |
m.n. | m is the minimum total width of the display and n is the number of digits after the decimal point (if available) |
Python2. Starting from 6, a new function str.format() for formatting strings is added, which enhances the function of string formatting.
7. Three quotation marks
Three quotation marks in Python can assign complex strings.
Python three quotation marks allow a string to span multiple lines, and the string can contain line breaks, tabs, and other special characters.
The syntax of three quotation marks is a pair of consecutive single quotation marks or double quotation marks (usually in pairs).
>>> hi = '''hi there''' >>> hi # repr() 'hi\nthere' >>> print hi # str() hi there
Three quotation marks free programmers from the quagmire of quotation marks and special strings, and keep a small string in the so-called WYSIWYG (what you see is what you get) format from beginning to end. A typical use case is that when you need a piece of HTML or SQL, it will be very troublesome to use the traditional escape character system when marked with three quotation marks.
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) ''')
8. Unicode string
Defining a Unicode string in Python is as simple as defining an ordinary string:
>>> u'Hello World !' u'Hello World !'
The lowercase "u" before the quotation marks indicates that a Unicode string is 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 replaced \ u0020 identifier indicates that a Unicode character (space character) with an encoding value of 0x0020 is inserted at the given position.