Python string
String is the most commonly used data type in Python. We can use quotes (' or ") to create strings.
Creating a string is as simple as assigning a value to a variable. For example:
var2 = "Python php"
Python accesses the value in the string
Python does not support single character types, and single characters are also used in Python Used as a string.
When accessing substrings in Python, you can use square brackets to intercept the string, as shown in the following example:
var1 = 'Hello World!'
var2 = "Python php"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
The above example execution result:
var2[1:5]: ytho
Python string update
You can modify an existing string and assign it to another variable, as shown in the following example:
# -*- coding: UTF-8 -*-
var1 = 'Hello World!'
print "Update string :- " , var1[:6] + 'php!'
Execution result of the above example
Python escape characters
When special characters need to be used in characters, Python uses backslash (\) to escape characters, as shown in the following table:
Python string operators
The value of instance variable a in the following table is the string "Hello", and the value of variable b is "Python":
Description | |
---|---|
Line continuation character | |
Backslash symbol | |
Single quote | |
Double quotes | |
Ring | |
Backspace | |
Escape | |
empty | ##\n |
\v | |
\t | |
\r | |
\f | |
\oyy | |
\xyy | |
\other | |
The example is as follows:
# -*- coding: UTF-8 -*-
a = "Hello"
b = "Python"
print "a + b Output result:", a + b
print "a * 2 Output result:", a * 2
print "a[1 ] Output result: ", a[1]
print "a[1:4] Output result: ", a[1:4]
if( "H" in a) :
print "H is in variable a"
else :
print "H is not in variable a"
if( "M" not in a) :
print "M is not in variable a "
else :
print "M is in variable a"
print r'\n'
print R'\n'
The above program is executed The result is:
a * 2 Output result: HelloHello
a[1] Output result: e
a[1:4] Output result : ell
H is in variable a
M is not in variable a
\n
\n
Python string formatting
Python supports formatted string output. Although this can lead to very complex expressions, the most basic usage is to insert a value into a string with the string formatting character %s.
In Python, string formatting uses the same syntax as the sprintf function in C.
The following example:
print "My name is %s and weight is %d kg!" % (' Zara', 21)
The above example output result:
python string Formatting symbols:
Operator | Description | Instance |
---|---|---|
String concatenation | a + b Output result: HelloPython | |
Repeated output string | a*2 Output result: HelloHello | |
Get the characters in the string by index | a[1] Output result | e |
Intercept part of the string | a[1:4] Output result | ell |
Member Operator - Returns True if the string contains the given character | H in aOutput result 1 | |
Member Operator - Returns True if the string does not contain the given character | M not in aOutput result 1 | |
Raw Strings - Raw Strings: All strings are used literally, without escaping special or unprintable characters. Raw strings have almost the same syntax as ordinary strings, except that the first quotation mark of the string is preceded by the letter "r" (can be uppercase or lowercase). | print r'\n'output\n andprint R'\n'output\n | |
Format string | Please see the next chapter |
Symbol | Description |
---|---|
%c | Format Characters and their ASCII codes |
## %s | Format string |
%d | Format integer |
Format unsigned integer | |
## Format unsigned Octal number | |
Formatted unsigned hexadecimal number | |
Format unsigned hexadecimal number (uppercase) | |
Format floating point numbers, you can specify the precision after the decimal point | |
Use scientific notation to format floating point numbers | ## %E |
Same function %e, format floating point number in scientific notation | %g |
Abbreviation for %f and %e | %G |
Abbreviations for %f and %E | |
## %p | Use ten Address of hexadecimal format variable |
Python triple quotes
Triple quotes in python can copy complex strings:
Python triple quotes allow a string to span multiple lines, characters Strings can contain newlines, tabs, and other special characters.
The syntax of triple quotes is a pair of consecutive single quotes or double quotes (usually used in pairs).
there'''
>>> hi # repr()
'hi\nthere'
>>> print hi # str()
hi
there
Three quotation marks free programmers from the quagmire of quotation marks and special strings, from beginning to end The format that holds a small piece of string is the so-called WYSIWYG (What You See Is What You Get) format.
A typical use case is when you need a piece of HTML or SQL, then using string combination, special string escaping will be very cumbersome.
Friends CGI Demo
;
ERROR
%s
'''
cursor.execute('''
CREATE TABLE users (
login VARCHAR(8),
uid INTEGER,
prid INTEGER)
''')
Unicode string
Defining a Unicode string in Python is as simple as defining a normal string:
The replaced \u0020 identifier means inserting the Unicode character (space character) with the encoding value 0x0020 at the given position.
Python's built-in string functions
String methods were slowly added from python1.6 to 2.0 - they were also added to Jython.
These methods implement most of the methods of the string module. The following table lists the methods currently supported by the built-in string. All methods include support for Unicode, and some are even specially used. for Unicode.
Function | |
---|---|
Define width or decimal point precision | |
Used for left alignment | |
Display plus sign (+) in front of positive numbers | |
Display a space before positive numbers | |
##Display zero ('0') before octal numbers, and '0' before hexadecimal numbers 0x' or '0X' (depending on whether 'x' or 'X' is used) | |
The displayed number is filled with '0' instead of the default The spaces | |
'%%' outputs a single '%' | |
Mapping variable (dictionary parameter) | |
m is the minimum total width of the display, n is the number of digits after the decimal point (if available) |
Method | Description | |
---|---|---|
string.capitalize() |
Capitalize the first character of the string |
|
string.center(width) |
Returns a new string with the original string centered and padded with spaces to length width |
|
string.count(str, beg=0, end=len(string)) |
Returns the number of times str appears in string. If beg or end is specified, the specified number is returned. The number of occurrences of str in the range |
|
##string.decode(encoding='UTF-8', errors='strict') | Decode the string in the encoding format specified by encoding. If an error occurs, a ValueError exception will be reported by default, unless errors specify 'ignore' or 'replace' | |
string.encode(encoding='UTF-8', errors='strict') | Encode string in the encoding format specified by encoding. If an error occurs, a ValueError exception will be reported by default. Unless errors specify 'ignore' or 'replace' | |
##string.endswith(obj, beg=0, end=len(string)) | Check whether the string ends with obj. If beg or end is specified, check whether the specified range ends with obj. If so, return True, otherwise return False.
||
Convert the tab symbols in the string string to spaces, tab The default number of spaces for symbols is 8. | ||
Check whether str is included in string. If beg and end specify the range, check whether it is included in the specified range. If it is, return the starting index value, otherwise return -1 |
||
The same as the find() method, only However, an exception will be reported if str is not in string. |
||
If string has at least If one character and all characters are letters or numbers, | returns True, otherwise returns False | ##string.isalpha()|
Returns True if string has at least one character and all characters are letters, | Otherwise returns False
string.isdecimal() | |
Returns True if string contains only decimal digits, otherwise returns False. |
string.isdigit() | |
Returns True if string only contains numbers, otherwise returns False. |
||
##string.islower() | If the string contains at least one case-sensitive character, and all these (case-sensitive) characters are lowercase, return True, otherwise return False | |
string.isnumeric() | If the string contains only numeric characters, return True, otherwise return False | |
string.isspace() | If the string contains only spaces, it returns True, otherwise it returns False. | |
string.istitle() | Returns True if string is titled (see title()), otherwise returns False | |
string.isupper() | If string contains at least one case-sensitive character, and all these (case-sensitive) characters If all are uppercase, return True, otherwise return False | |
##string.join(seq) | Use string as the separator to combine all elements (string representations) in seq into a new string
||
Returns a new string with the original string left-aligned and padded with spaces to length width | ||
Convert all uppercase characters in string to lowercase. | ||
Truncate the spaces on the left side of string | ||
The maketrans() method is used to create a conversion table for character mapping. For the simplest calling method that accepts two parameters, the first parameter is a string representing the characters that need to be converted, and the second parameter Also the target of string representation conversion. | ||
Returns the largest letter in the string | str. |
|
Returns the smallest letter in the string | str. |
|
A bit like find() and split( ), starting from the first position where str appears, divide the string string into a 3-element tuple (string_pre_str, str, string_post_str). If string does not contain str, string_pre_str == string. |
||
Replace str1 in string with str2. If num is specified, the replacement will not exceed num times. |
##string.rfind(str, beg=0,end=len (string) ) | |
Similar to the find() function, but starting from the right. | string. rindex(str, beg=0,end=len(string)) | |
Similar to index(), but starts from the right. | string.rjust(width) | |
Returns a new string with the original string right-aligned and padded with spaces to length width | string.rpartition(str) | |
Similar to the partition() function, but starts searching from the right. | string.rstrip() | Remove the spaces at the end of the string string. |
##string.split(str="", num=string .count(str)) |
Use str as the separator to slice string. If num has a specified value, only num substrings will be separated | |
string.splitlines(num=string.count('\n')) | Separate by row, return a list containing each row as an element , if num is specified, only num rows will be sliced. | |
string.startswith(obj, beg=0,end=len(string)) | Check whether the string starts with obj, if so, return True, otherwise return False. If beg and end specify values, check within the specified range. | |
string.strip([obj]) |
Execute lstrip() and rstrip() on string | |
Reverse case in string | ||
Return "titled" string, that is to say, all words start with uppercase, and the remaining letters are lowercase (see istitle()) | ||
string.translate(str , del="") | Convert the characters of string according to the table given by str (containing 256 characters),
put the characters to be filtered out In the del parameter |
|
Convert the lowercase letters in string to uppercase | ||
Returns a string with a length of width. The original string string is right-aligned and filled in front. 0 | ||
The isdecimal() method checks whether a string contains only decimal characters. This method only exists for unicode objects. |