Python3 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:

var1 = 'Hello World!'
var2 = "php"

Python Access Characters Values ​​in strings

Python does not support single character types. Single characters are also used as a string in Python.

Python can use square brackets to intercept strings. The following example:

#!/usr/bin/python3

var1 = 'Hello World!'
var2 = "php"

print ("var1[0]: ", var1[0])
print ("var2[1:5]: ", var2[1:5])

The execution result of the above example:

var1[0]:  H
var2[1:5]:  unoo

Python string update

You can modify the existing string and assign it to another A variable, as shown in the following example:

#!/usr/bin/python3

var1 = 'Hello World!'

print ("已更新字符串 : ", var1[:6] + 'php!')

Execution results of the above example

已更新字符串 :  Hello php!

Python escape characters

When special characters need to be used in characters, python uses reverse Slash (\) escape characters, as shown in the following table:

##Escape characterDescription##\(At the end of the line)\\\'\"# #\aRing\bBackspace\eEscape\000Empty\nNewline\vVertical tab character\tHorizontal tab character\rEnter\fPage changeOctal number, the character represented by yy, for example: \o12 represents newline Hexadecimal number, yy represents Characters, for example: \x0a represents line break Other characters are output in normal format
Line continuation character
Backslash character
Single quotes
Double quotes
## \oyy
\xyy
\other

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":

##+String concatenationa + b Output result: HelloPython* Repeated output string a*2 Output result: HelloHello[]Get the characters in the string by indexa[1] Output result[ : ] Intercept part of the stringa[1:4] Output resultinMember Operator - Returns True if the string contains the given character not inMember Operator - Returns True if the string does not contain the given character r/RRaw 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). ##% Example
OperatorDescriptionInstance
e
ell
H in a Output result 1
M not in a Output result 1
print r'\n' prints \n and print R'\n' prints \n
Format stringPlease see the next section.
#!/usr/bin/python3

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 output result of the above example 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 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 examples:

#!/usr/bin/python3

print ("我叫 %s 今年 %d 岁!" % ('小明', 10))

The output results of the above examples:

我叫 小明 今年 10 岁!

Python string formatting symbols:

<tbody

## %u Format unsigned integer %o %x %X %f %e## %E %g %G
Symbol Description
%c Format Characters and their ASCII codes
## %s Format string
%d Format 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
Same function %e, format floating point number in scientific notation
Abbreviation for %f and %e
Abbreviations for %f and %E
## %p Use ten Address of hexadecimal format variable
Format operator auxiliary command:

symbol Function*Define width or decimal point precision- Used for left alignment+Display plus sign (+) in front of positive numbers<sp>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) 0The displayed number is filled with '0' instead of the default The spaces %'%%' outputs a single '%'(var)Mapping variable (dictionary parameter)##m.n.

Python triple quotes

Python triple quotes allow a string to span multiple lines, and the string can contain newlines, tabs, and other special characters. The example is as follows

#!/usr/bin/python3

para_str = """这是一个多行字符串的实例
多行字符串可以使用制表符
TAB ( \t )。
也可以使用换行符 [ \n ]。
"""
print (para_str)

The execution result of the above example is:

这是一个多行字符串的实例
多行字符串可以使用制表符
TAB (    )。
也可以使用换行符 [ 
 ]。

Three quotation marks free programmers from the quagmire of quotation marks and special strings. Maintaining the format of a small string from beginning to end 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.

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 string

In Python2, ordinary strings are stored as 8-bit ASCII codes, while Unicode strings are stored as 16-bit unicode strings, so Able to represent more character sets. The syntax used is to prefix the string with u.

In Python3, all strings are Unicode strings.


Python’s string built-in functions

Python’s commonly used string built-in functions are as follows:


m is the minimum total width of the display, n is the number of digits after the decimal point (if available)
##17##18join(seq)19len(string)20ljust(width[, fillchar])21lower()22lstrip()23maketrans()24max(str)25min(str)26replace(old, new [, max])27rfind(str, beg=0,end=len(string))28rindex(str, beg=0, end=len(string))29rjust(width,[, fillchar])30rstrip()31split(str="", num=string.count(str)) 32splitlines( num=string. count('\n'))
Serial numberMethod and description
1

capitalize()
Change the first character of the string characters are converted to uppercase

2

center(width, fillchar)


Returns a specified width width centered String, fillchar is the filling character, and the default is space.
3

count(str, beg= 0,end=len(string))


Returns the occurrence of str in string The number of times, if beg or end is specified, returns the number of occurrences of str in the specified range
4

decode(encoding='UTF-8',errors= 'strict')


Use the specified encoding to decode the string. The default encoding is string encoding.
5

encode(encoding='UTF-8',errors='strict')


The encoding format specified by encoding Encoded string, if an error occurs, a ValueError exception will be reported by default, unless errors specify 'ignore' or 'replace'
6

endswith(suffix , 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.

7

expandtabs(tabsize=8)


Convert the tab symbols in the string string to spaces, tab symbols The default number of spaces is 8.
8

find(str, beg=0 end=len(string))


Detect whether str is included in the string , if beg and end specify a range, check whether it is included in the specified range, if so, return the starting index value, otherwise return -1
9

index(str, beg=0, end=len(string))


Same as find() method, except that if str is not in the string, an exception will be reported.
10

isalnum()


Returns if the string has at least one character and all characters are letters or numbers Return True, otherwise return False
11

isalpha()


Returns True if the string has at least one character and all characters are letters, Otherwise it returns False
12

isdigit()


If the string contains only digits, it returns True, otherwise it returns False..
13

islower()


If the string contains at least one case-sensitive character, and all of them (case-sensitive ) characters are all lowercase, it returns True, otherwise it returns False
14

isnumeric()


If the string only contains Numeric characters, returns True, otherwise returns False
15

isspace()


If the string contains only spaces, then Returns True, otherwise False.
16

istitle()


If the string is titled (see title() ) returns True, otherwise returns False
isupper()

If the string contains at least one case-sensitive characters, and all these (case-sensitive) characters are uppercase, return True, otherwise return False

Use the specified string as the delimiter to combine all elements (string representations) in seq into a new string


Return the string length


Returns a new string that is left-aligned to the original string and filled to length width using fillchar. Fillchar defaults to spaces.


Convert all uppercase characters in the string to lowercase.


Truncate the spaces on the left side of the string


Create a conversion table for character mapping. For the simplest calling method that accepts two parameters, the first parameter is a string, indicating the characters that need to be converted, and the second parameter is also a string. Indicates the target of conversion.


Returns the largest letter in the string str.


Returns the smallest letter in the string str.


Replace str1 in the string with str2, if If max is specified, the replacement will not exceed max times.


Similar to the find() function, But it starts searching from the right.


Similar to index(), but starts from the right.


Return An original string is right-aligned and filled with fillchar (default spaces) to a new string of length width


Remove spaces at the end of string string.


num=string.count(str)) Use str as the separator to intercept the string. If num has a specified value, only num substrings will be intercepted



Separated by rows, return a list containing each row as an element. If num is specified, only num rows will be sliced.
33

startswith( str, 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, the specified range is checked.
34

strip([chars])


Execute lstrip() and rstrip() on strings
35

swapcase()


Convert uppercase to lowercase in the string and convert lowercase to uppercase
36

title()


Returns a "titled" string, that is, all words start with uppercase letters, and the remaining letters are lowercase (see istitle() )
37

translate(table, deletechars="")


The table given by str (contains 256 characters) Convert string characters, The characters to be filtered out are placed in the deletechars parameter
38

upper()


Convert the lowercase letters in the string to uppercase
39

zfill (width)


Returns a string with a length of width. The original string is right-aligned and filled with 0
40

isdecimal()


Checks whether the string contains only decimal characters, if so it returns true, otherwise it returns false.