author : Han Xinzi @ShowMeAI
Tutorial address :http://www.showmeai.tech/tutorials/56
This paper addresses :http://www.showmeai.tech/article-detail/76
Statement : copyright , For reprint, please contact the platform and the author and indicate the source
The string is Python The most commonly used data type in . We can use quotation marks (' or ") To create a string .
Creating a string is simple , Just assign a value to the variable . for example :
str1 = 'Hello ShowMeAI!' str2 = "Python ShowMeAI"
Python Single character type... Is not supported , The single character is in Python Is also used as a string .Python Access substring , You can use square brackets with indexes to slice strings .
Here's a code example ( The code can be in On-line python3 Environmental Science Run in ):
str1 = 'Hello World!' str2 = "Python ShowMeAI" print("str1[0]: ", str1[0]) #index by 0 The characters of print("str2[1:5]: ", str2[1:5]) # from index by 1 Start to 5 end ( It doesn't contain 5)
The execution result of the above example :
str1[0]: H str2[1:5]: ytho
We can intercept the string and connect it with other strings , Here's a code example ( The code can be in On-line python3 Environmental Science Run in ):
str1 = 'Hello World!' print(" Output :", str1[:6] + 'ShowMeAI!')
The execution result of the above example :
Output : Hello ShowMeAI!
When special characters need to be used in characters ,python Use the backslash \ Escape character . The following table :
Escape character
describe
( When at the tail )
Line continuation operator
\
Backslash notation
\'
Single quotation marks
\"
Double quotes
\a
Ring the bell
\b
Backspace (Backspace)
\e
escape
\000
empty
\n
Line break
\v
Vertical tabs
\t
Horizontal tabs
\r
enter
\f
Change the page
\oyy
Octal number ,y representative 0~7 The characters of , for example :\012 On behalf of the line .
\xyy
Hexadecimal number , With \x start ,yy Representative character , for example :\x0a On behalf of the line
\other
The other characters are output in normal format
The following table shows the instance variables a The value is a string "Hello",b Variable value is "Python":
The operator
describe
example
String connection
a + b 'HelloPython'
Repeat output string
a * 2 'HelloHello'
[]
Get the characters in the string by index
a1 'e'
:
To intercept a part of a string
a1:4 'ell'
in
member operator - If the string contains the given character, it returns True
"H" in a True
not in
member operator - If the string does not contain the given character True
"M" not in a True
r/R
Original string - Original string : All strings are used literally , No escaping special or non printable characters . The original string is divided by the letter before the first quotation mark of the string "r"( It can be written in case ) outside , It has almost the same syntax as ordinary strings .
print r'\n' \n >>> print R'\n' \n
%
Format string
Please see the following content
Here's a code example ( The code can be in On-line python3 Environmental Science Run in ):
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 variables 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 variables a in ") print(r'\n') print(R'\n')
The execution result of the above example :
a + b Output results : HelloPython a * 2 Output results : HelloHello a[1] Output results : e a[1:4] Output results : ell H In variables a in M Not in variable a in \n \n
Python Support output of formatted string .
The most basic usage is to insert a value into a string formatter %s In the string of .
stay Python in , String formatting uses C in sprintf Function like syntax .
The following example ( The code can be in On-line python3 Environmental Science Run in ):
print("The website is %s and the author's age is %d!" % ('ShowMeAI', 30) )
The execution result of the above example :
The website is ShowMeAI and the author's age is 30!
python String formatting symbols :
operator Number
describe
%c
Format characters and their ASCII code
%s
Formatted string
%d
Formatted integer
%u
Format an unsigned integer
%o
Format an unsigned octal number
%x
Formats unsigned hexadecimal Numbers
%X
Formats unsigned hexadecimal Numbers ( Capitalization )
%f
Formatted floating point number , Precision after the decimal point can be specified
%e
Scientific notation for formatting floating - point Numbers
%E
Work with %e, Scientific notation for formatting floating - point Numbers
%g
%f and %e Abbreviation
%G
%F and %E Abbreviation
%p
Format the address of a variable with a hexadecimal number
Formatting operator helper :
Symbol
function
Define width or decimal precision
Use for left alignment
Show a plus sign before a positive number ( + )
<sp>
Show spaces before positive numbers
Show zero before octal number ('0'), Show... In front of hex '0x' perhaps '0X'( It depends on what you use 'x' still 'X')
0
Fill in the front of the displayed number '0' Not the default space
%
'%%' Output a single '%'
(var)
Mapping variables ( Dictionary parameters )
m.n.
m Is the minimum overall width of the display ,n It's the number of decimal places ( If available )
Python There is also a function for formatting strings str.format(), It enhances string formatting , The basic grammar is through {} and : To replace the old % .
format Function can take any number of arguments , Positions can be out of order .
>>>"{} {}".format("hello", "ShowMeAI") # Does not set the specified location , By default 'hello ShowMeAI' >>> "{0} {1}".format("hello", "ShowMeAI") # Set the specified location 'hello ShowMeAI' >>> "{1} {0} {1}".format("hello", "ShowMeAI") # Set the specified location 'ShowMeAI hello ShowMeAI'
You can also set parameters :
print(" The websites :{name}, Address {url}".format(name="ShowMeAI Knowledge community ", url="www.showmeai.tech")) # Set the parameters through the dictionary site = {"name": "ShowMeAI Knowledge community ", "url": "www.showmeai.tech"} print(" The websites :{name}, Address {url}".format(**site)) # Set the parameters by the list index my_list = ['ShowMeAI Knowledge community ', 'www.showmeai.tech'] print(" The websites :{0[0]}, Address {0[1]}".format(my_list)) # "0" Is a must
The code runs as
The websites :ShowMeAI Knowledge community , Address www.showmeai.tech The websites :ShowMeAI Knowledge community , Address www.showmeai.tech The websites :ShowMeAI Knowledge community , Address www.showmeai.tech
format You can also format numbers , The following table shows str.format() There are many ways to format numbers :
>>> print("{:.2f}".format(3.1415926)) 3.14
Numbers
Format
Output
describe
3.1415926
{:.2f}
3.14
Keep two decimal places
3.1415926
{:+.2f}
+3.14
Keep two decimal places with symbols
-1
{:+.2f}
-1.00
Keep two decimal places with symbols
2.71828
{:.0f}
3
Without decimals
5
{:0>2d}
05
Zero up the number ( Fill left , Width is 2)
5
{:x<4d}
5xxx
Number complement x ( Fill the right side , Width is 4)
10
{:x<4d}
10xx
Number complement x ( Fill the right side , Width is 4)
1000000
{:,}
1,000,000
Comma separated number format
0.25
{:.2%}
25.00%
Percentage format
1000000000
{:.2e}
1.00e+09
Index notation
13
{:>10d}
13
Right alignment ( Default , Width is 10)
13
{:<10d}
13
Align left ( Width is 10)
13
{:^10d}
13
Align in the middle ( Width is 10)
11
'{:b}'.format(11)
'{:d}'.format(11)
'{:o}'.format(11)
'{:x}'.format(11)
'{:#x}'.format(11)
'{:#X}'.format(11)
10
11
11
13
b
0xb
0XB
Base number
^, <, > They're centered 、 Align left 、 Right alignment , Width of back band , : Number followed by a filled character , It can only be one character , If it is not specified, it is filled with spaces by default .
+ Indicates that... Is displayed before a positive number +, Display before negative number -; ( Space ) Means adding a space before a positive number
b、d、o、x They're binary 、 Decimal system 、 octal 、 Hexadecimal .
In addition, we can use braces {} To escape braces , The following code example ( The code can be in On-line python3 Environmental Science Run in ):
print("{} The corresponding priority is {{0}}".format("ShowMeAI"))
The execution result of the above example :
ShowMeAI The corresponding priority is {0}
Python The middle three quotation marks can assign complex strings .
Python Three quotes allow a string to span multiple lines , 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 , Maintaining the format of a small string throughout is called WYSIWYG( What you see is what you get ) Format .
A typical use case is , When you need a piece of HTML perhaps SQL when , In this case, mark with three quotation marks , Using the traditional escape character system will be very laborious .
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) ''')
Python Define a Unicode A string is as simple as defining an ordinary string :
>>> u'Hello World !' u'Hello World !'
Lowercase before quotation marks "u" Indicates that what is created here is a Unicode character string . If you want to add a special character , have access to Python Of Unicode-Escape code . As shown in the following example :
>>> u'Hello\u0020World !' u'Hello World !'
Replaced by \u0020 The identifier indicates that the code value inserted at the given position is 0x0020 Of Unicode character ( Space character ).
The string method is from python1.6 To 2.0 Add it slowly —— They are also added to Jython in .
These methods realize string Most methods of modules , The following table lists the methods currently supported by string built-in , All methods include a pair of Unicode Support for , Some are even dedicated to Unicode Of .
Method
describe
string.capitalize()
Capitalize the first character of a string
string.center(width)
Returns an original string centered , And fill it with Spaces to length width New string of
string.count(str, beg=0, end=len(string))
return str stay string The number of times it's inside , If beg perhaps end If specified, return to the specified range str Number of occurrences
string.decode(encoding='UTF-8', errors='strict')
With encoding Decoding the specified encoding format string, If there is an error, one will be reported by default ValueError Of different often , Unless errors finger set Of yes 'ignore' or person 'replace'
string.encode(encoding='UTF-8', errors='strict')
With encoding Code the specified encoding format string, If there is an error, one will be reported by default ValueError It's abnormal , Unless errors Specifies the 'ignore' perhaps 'replace'
string.endswith(obj, beg=0, end=len(string))
Check whether the string uses obj end , If beg perhaps end Specify to check whether the specified range is in the range of obj end , If it is , return True, Otherwise return to False.
string.expandtabs(tabsize=8)
Put the string string Medium tab Turn the symbol into a space ,tab The default number of spaces for symbols is 8.
string.find(str, beg=0, end=len(string))
testing str Is it included in string in , If beg and end Specified scope , Then check whether it is included in the specified range , If it's returning the starting index value , Otherwise return to -1
string.format()
Formatted string
string.index(str, beg=0, end=len(string))
Follow find() The method is the same , Just if str be not in string An exception will be reported in .
string.isalnum()
If string Returns at least one character and all characters are letters or Numbers True, Otherwise return to False
string.isalpha()
If string Returns at least one character and all characters are letters True, Otherwise return to False
string.isdecimal()
If string Contains only decimal digits and returns True Otherwise return to False.
string.isdigit()
If string Only Numbers are returned True Otherwise return to False.
string.islower()
If string Contains at least one case-sensitive character , And all of this ( case-sensitive ) All characters are lowercase , Then return to True, Otherwise return to False
string.isnumeric()
If string Contains only numeric characters , Then return to True, Otherwise return to False
string.isspace()
If string Contains only Spaces , Then return to True, Otherwise return to False.
string.istitle()
If string It's titled ( see title()) Then return to True, Otherwise return to False
string.isupper()
If string Contains at least one case-sensitive character , And all of this ( case-sensitive ) All characters are uppercase , Then return to True, Otherwise return to False
string.join(seq)
With string As a separator , take seq All the elements in ( String representation of ) Merge into a new string
string.ljust(width)
Returns an original string left aligned , And fill it with Spaces to length width New string of
string.lower()
transformation string All uppercase characters are lowercase .
string.lstrip()
Cut off string Space on the left
string.maketrans(intab, outtab])
maketrans() Method to create a conversion table for character mapping , For the simplest call to accept two parameters , The first parameter is the string , Indicates the character to be converted , The second parameter is also the target of string representation transformation .
max(str)
Return string str The largest letter in .
min(str)
Return string str The smallest letter in .
string.partition(str)
It's kind of like find() and split() The combination of , from str The first place to appear is , hold word operator strand string branch become One individual 3 element plain Of element Group (string_pre_str,str,string_post_str), If string Contains no str be string_pre_str == string.
string.replace(str1, str2, num=string.count(str1))
hold string Medium str1 Replace with str2, If num Appoint , The substitution does not exceed num Time .
string.rfind(str, beg=0,end=len(string) )
Be similar to find() function , Returns the last occurrence of a string , If there is no match, return -1.
string.rindex( str, beg=0,end=len(string))
Be similar to index(), It's just from the right .
string.rjust(width)
Returns an original string to the right , And fill it with Spaces to length width New string of
string.rpartition(str)
Be similar to partition() function , Just search from the right
string.rstrip()
Delete string Space at end of string .
string.split(str="", num=string.count(str))
With str Slice for separator string, If num There is a specified value , Only separate num+1 Substring
string.splitlines([keepends])
Follow the line ('\r', '\r\n', \n') Separate , Returns a list of rows as elements , If parameters keepends by False, Does not contain line breaks , If True, Keep the newline .
string.startswith(obj, beg=0,end=len(string))
Check if the string is set to obj start , Yes, go back to True, Otherwise return to False. If beg and end Specify the value , Check... Within the specified range .
string.strip([obj])
stay string On the implementation lstrip() and rstrip()
string.swapcase()
Flip string Case in
string.title()
return " The title is changed " Of string, That means all words begin with a capital letter , The rest of the letters are lowercase ( see istitle())
string.translate(str, del="")
according to str The table given ( contain 256 Characters ) transformation string The characters of , Put the filtered characters in del Parameters in
string.upper()
transformation string The lowercase letter in is uppercase
string.zfill(width)
Return length is width String , Original string string Right alignment , Fill in the front 0
Please click to B I'm looking at it from the website 【 Bilingual subtitles 】 edition
https://www.bilibili.com/video/BV1yg411c7Nw
The code for this tutorial series can be found in ShowMeAI Corresponding github Download , Can be local python Environment is running , Babies who can visit foreign websites can also directly use google colab One click operation and interactive operation learning Oh !
This tutorial series covers Python The quick look-up table can be downloaded and obtained at the following address :