May 10, 2021 Python2
Strings are the most commonly used data types in Python. We can use quotation marks to create strings.
Creating a string is as simple as assigning a value to a variable. For example:
var1 = 'Hello World!'
var2 = "Python w3cschool"
Python does not support single-character types, and single-character characters are also used as a string in Python.
Python accesses substrings, which can be intercepted using square brackets, as follows:
#!/usr/bin/python
var1 = 'Hello World!'
var2 = "Python w3cschool"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
The results of the above example execution:
var1[0]: H
var2[1:5]: ytho
You can modify an existing string and assign it to another variable, as follows:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
var1 = 'Hello World!'
print "更新字符串 :- ", var1[:6] + 'w3cschool!'
The above instance executes the results
更新字符串 :- Hello w3cschool!
When you need to use special characters in characters, Python escapes characters with a backslash. Here's the table:
Escape characters | Describe |
---|---|
(at the end of the line) | The line break |
\\ | Backslash symbol |
\' | Single quotes |
\" | Double quotes |
\a | Bell |
\b | Backspace |
\e | Escape |
00 | Empty |
\n | Line change |
\v | Vertical tabs |
\t | Landscape tabs |
\r | Enter |
\f | Change the page |
\oyy | Octal number, yy for the character, e.g.: so12 for line changes |
\xyy | Hex, yy for characters, e.g.: sx0a for line changes |
\other | Other characters are output in normal format |
The following table example variable a value is the string "Hello" and the b variable value is "Python":
Operator | Describe | Instance |
---|---|---|
+ | String connection | A-b Output: HelloPython |
* | Repeat the output string | a :2 Output: Hello Hello |
[] | Get the characters in the string through the index | The output e |
[ : ] | Intercept a portion of the string | a s1:4 s output ell |
in | Member Operator - True if the string contains a given character | H in a output 1 |
not in | Member Operator - True if the string does not contain a given character | M not in a output 1 |
r/R | Original String - Original String: All strings are used literally, with no escaped special or unprintable characters. The original string has an almost identical syntax to a normal string, except that it has the letter "r" (caseable) before the first quotation mark of the string. | print r'n' prints'n and print R'n'prints' |
% | The format string | Let's take a look at the next section |
Here's an example:
#!/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 procedures are performed as follows:
a + b 输出结果: HelloPython
a * 2 输出结果: HelloHello
a[1] 输出结果: e
a[1:4] 输出结果: ell
H 在变量 a 中
M 不在变量 a 中
\n
\n
Python supports formatting the output of strings. Although this may use very complex expressions, the most basic use is to insert a value into a string with the string format %s.
In Python, string formatting uses the same syntax as the sprintf function in C.
Here's an example:
#!/usr/bin/python
print "My name is %s and weight is %d kg!" % ('Zara', 21)
The above example output results:
My name is Zara and weight is 21 kg!
Python string formatting symbol:
the number of the character | Describe |
---|---|
%c | Format characters and their ASCII codes |
%s | Format the string |
%d | Format the integer |
%u | Format unsigned integers |
%o | Format the unsigned octal number |
%x | Format the unsigned hete sixteenths |
%X | Format unsigned heteens (capital) |
%f | Format floating-point numbers to specify the accuracy after the scale |
%e | Format floats with scientific notation |
%E | Acting like %e, floating points are formatted by scientific notation |
%g | A short history of %f and %e |
%G | Short case of %f and %E |
%p | Format the address of the variable in hete sixteenths |
Format operator auxiliary instructions:
Symbol | Function |
---|---|
* | Define width or scale accuracy |
- | Use to make left alignment |
+ | Show the plus sign in front of the positive number ( . . . |
<sp> | Spaces are displayed before the positive number |
# | Show zero ('0') in front of octals, '0x' or '0X' in front of hex (depending on whether 'x' or 'X' is used) |
0 | The displayed number is filled with '0' instead of the default space |
% | '%%' outputs a single '%' |
(var) | Map variables (dictionary parameters) |
m.n. | m is the minimum total width displayed, n is the number of digits after the scale (if available) |
Three quotation marks in Python can copy complex strings:
Python three quotation marks allow a string to span multiple lines, and a string can contain line breaks, tabs, and other special characters.
The syntax of three quotation marks is a pair of consecutive single or double quotation marks (usually in pairs).
>>> hi = '''hi
there'''
>>> hi # repr()
'hi\nthere'
>>> print hi # str()
hi
there
The three quotation marks free the programmer from the quagmire of quotation marks and special strings, keeping a small string in the format of the so-called WYSIWYG (WYSIWYG) format from start to finish.
A typical use case is when you need an HTML or SQL, and with string combinations, special string escapes can be cumbersome.
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)
''')
Defining a Unicode string in Python is as simple as defining a normal string:
>>> u'Hello World !'
u'Hello World !'
A "u" in pre-quotes indicates that a Unicode string is created here. I f you want to add a special character, you can use Python's Unicode-Escape encoding. Here's an example:
>>> u'Hello\u0020World !'
u'Hello World !'
The replaced .u0020 identity represents the insertion of a Unicode character (space character) with an encoded value of 0x0020 at a given location.
String methods are slowly added from Python 1.6 to 2.0 -- they are also added to Jython.
These methods implement most of the methods of the string module, and list the methods currently supported by string built-in as shown in the following table, all of which include support for Unicode, some even specifically for Unicode.
Method | Describe |
---|---|
Capital the first character of the string |
|
Returns a new string with the original string centered and filled with spaces to the length width |
|
Returns the number of times str appears in the string, and returns the number of str appearances within the specified range if the beg or end specifies |
|
Decode the string in the encoding format specified by encoding, and if an error is reported by default to a ValueError anomaly, except that non-errors refer to 'ignore' or 'replace' |
|
Encode string in encoding-specified format, if an error is reported by default to a ValueError exception, unless the errors specify 'ignore' or 'replace' |
|
Check whether the string ends with obj, check if the specified range ends with obj if it is specified, or true if so, or false. |
|
Turn the tab symbol in string string into a space, and the default number of spaces tabsize is 8. |
|
Detects whether str is included in the string, if beg and end specify a range, then checks whether it is included in the specified range, or -1 is returned if the index value from the beginning is returned |
|
It's the same as the find() method, except that if str doesn't report an exception in string. |
|
Returns if the string has at least one character and all characters are letters or numbers True, or false |
|
True if the string has at least one character and all characters are letters. Otherwise, false is returned |
|
If string contains only a hedding number, true is returned or False is returned. |
|
If string contains only numbers, true is returned or False is returned. |
|
True is returned if the string contains at least one case-sensitive character, and all of these (case-sensitive) characters are small case |
|
If only numeric characters are included in the string, True is returned, otherwise False is returned |
|
If only spaces are included in the string, true is returned, otherwise False is returned. |
|
True if string is titled (see title()), otherwise false is returned |
|
True is returned if the string contains at least one case-sensitive character, and all of these case-sensitive characters are capitals |
|
Merges merges all the elements in seq (represented by strings) into a new string using string as a separator |
|
Returns a new string with the original string aligned to the left and filled with spaces to the length width |
|
Convert all capital characters in string to small. |
|
Cut off the space on the left side of the string |
|
The maketrans() method is used to create a conversion table for character mapping, and for the simplest way to accept two arguments, the first argument is a string, representing the characters that need to be converted, and the second argument is the target of the string representing the conversion. |
|
Returns the largest letter in the string str. |
|
Returns the smallest letter in the string str. |
|
A bit like a combination of find() and split(), from the first position where str appears, the string string is divided into a 3-dollar group (string_pre_str, str, string_post_str), and if the string does not contain str then string_pre_str is string. |
|
Replace str1 in string with str2 and, if specified by num, no more than num. |
|
Similar to a find() function, but looking from the right. |
|
Similar to index(), but starting from the right. |
|
Returns a new string with the original string aligned to the right and filled with spaces to the length width |
|
string.rpartition(str) |
Similar to the partition() function, but starting from the right. |
Remove the space at the end of the string. |
|
The separator slice string is str, and if num has a specified value, only num substrings are separated |
|
Separated by rows, returns a list that contains the rows as elements and slices only num rows if specified by num. |
|
Check if the string starts with obj and returns True, otherwise false is returned. If beg and end specify values, check within the specified range. |
|
Perform lstrip() and rstrip() on string |
|
Flip the case in the string |
|
Returns a "titled" string, which means that all words start in capitals and the rest of the letters are lowercase (see isitle()) |
|
Convert the characters of the string based on the table given by str, which contains 256 characters. The characters to filter out are placed in the del parameter |
|
Convert lowercase letters in string to capital |
|
Returns a string with a length of width, the original string string is aligned to the right and is filled with 0 in front |
|
The isdecimal() method checks whether the string contains only adip characters. This method exists only in unicode objects. |