Reference link: How to check whether a string is a valid keyword in Python?
Str string in Python
Features:
A string is an ordered set of characters. Use single quotes ['], double quotes ["], triple quotes [""" or ``']. Strings are immutable objects since Python 3.0, and strings are of Unicode type ( utf8)
Declaration method
str1 = 'string'
str2 = "string2"
str3 = '''this's a "string" '''
str4 = """select * from user where name = 'xdd' """
Symbols used with strings
[\N] Newline symbol [\t] is equivalent to TAB key [r”” or R””] means that special symbols in the string are not translated
For example: str5 = r”hello \n xdd” commonly used translation characters are
Common method
join(iterable)->str Link the iterable object using the specified character [string] into a new character and return. (Note: the iterable object itself is a string)
iterable is an iterable object replace(old,new[,count])->str #Replace the string matching old in the character with a new string
old The character to be replaced new Replace the character count The number of replacements, if not specified, replace all strip([chars])->str # Remove all characters in the custom character set chars from both ends of the custom string, if chars is not specified , Remove the blank characters at both ends
chars cutter
Find characters
find(sub[,start[,end]])->int #Find the string sub in the specified interval [start, end), from left to right. Return index if found, return -1 if not found
sub The string to be searched start Find the starting point index end Find the end index of the interval (not including the end index) rfind(sub[,start[,end]])->int #In the specified interval [start,end) from right to Left, find the string sub, find the return index, if not found, return -1
sub The string to find start The starting point index to find end The end index of the interval to find (not including the end index) index(sub[,start[,end]])->int #In the specified interval [start,end ), from left to right, find the substring sub. Find the return index, throw an exception ValueError if not found (if start and end are not set, search in the entire string)
sub The string to be searched start The start index of the search interval end The end index of the search interval (not including the end index) rindex(sub[,start[,end]])->int #In the specified interval [start,end) , From right to left, find the substring sub. Find the return index, throw an exception ValueError if not found (if start and end are not set, search in the entire string)
sub The string to be searched start The start index of the search interval end The end index of the search interval (not including the end index)
Statistical judgment
count(sub[,start[,end]])->int #In the specified interval [start,end), from left to right, count the number of times the substring sub appears (if there is no custom start and end, the default is in the entire string Statistics)
sub The string to be counted start The start index of the statistics end The end index of the statistics (not including the end index) endswith(suffix[,start[,end]])->bool #In the specified interval [start,end), string Whether it is the end of a suffix character, whether it returns True or not returns False. If you do not specify a range, the default range is the entire string startswith(prefix[,start[,end]])->bool #In the specified range [start,end), whether the string starts with prefix. If the interval is not specified, the default interval is whether the entire string isalnum()->bool is composed of letters and numbers isalpha()->bool is alphabetic isdecimal()->bool whether it contains only decimal numbers isdigit()->bool Whether all numbers (0-9) isidentifier()->bool start with an underscore, the others are letters, numbers, and underscores islower()->bool are all lowercase isupper()->bool are all uppercase isspace() ->bool contains only white space characters
Cutting character class
split(sep=None,maxsplit=-1) -> list collection of str type, use custom characters to cut the string
Use custom characters to cut the string, and return the cut character array sep to specify the cut string. By default, the blank symbol is the cut symbol. maxsplit specifies the number of splits, -1 means to traverse the entire string splitlines(keepends)->str type list collection, use lines to split the string
Use lines to cut characters, line separators include [\n][\r\n][\r], etc. Keepends refers to whether to keep the line separators, not by default (default: keepends=False) partition(sep)-> (head,sep,tail) Cut the string and return a triplet. (Cut from left to right)
Sep cutting symbol, you must specify the specified character to be cut from left to right into a triple consisting of the head, the separator, and the tail; if the separator is not found, only the ternary of the head and 2 empty elements is returned group. rpartition(sep)->(head,sep,tail) cut the string and return a triple (cut from right to left)
Cut the specified character from right to left into triples consisting of three parts: head, separator, and tail; if no separator is found, return 2 empty elements and a tail triple
Case conversion class
upper()->str #Convert all characters in a character to uppercase lower()->str #Convert all characters in a character to lowercase swapcase()->str #Convert uppercase to lowercase and lowercase to uppercase capitalize ()->str #Convert the first letter of the first word in the string into uppercase letters title()->str #Convert the first letter of each letter in the English word into uppercase letters
Position adjustment
center(width[,fillchar])->str #Display the character string in the center according to the specified width. Blank positions are filled with fillchar. The default value is the space symbol
width Total width fillchar Filled characters (cannot be a string) zfill(width)->str #Display the specified characters on the right according to width. Use 0 padding for insufficient places
width: print width, right side and left side filled with 0 ljust(width[.fillchar])->str # align the characters to the left and display the width length, use fillchar bytes instead of lengths.
width: print width fillchar: supplementary characters rjust(width[,fillchar])->str # align the characters to the right and display the width length, not enough to use fillchar bytes instead.
String formatting
C language style string format
Before version 2.5, you can only use printf style print output
printf-style formatting, from the C language printf function format requirements:
Placeholder: Use% and format characters. For example, %s, %d, etc.
s calls star() and r calls repr(). All objects can be transformed by these two. You can also insert modified characters in the station position. For example, %03d means that the length of the printed character is 3, and the signature is not enough to fill in 0format% values. The format string and the value to be formatted can only be separated by %. Values can only be an object; or A tuple equal to the number of placeholders in the format string, or a dictionary example No1
["%D get me %f"% (20,20.222)] The output result is: '20 get me 20.222000' Example No2
["I an %03d"% 20] is also equivalent to ["I am %03d"% (20,)] where: %03d outputs an integer. When the number of significant digits of the integer is less than 3, add 0 in front of the number. Example No3
["I like %s"%'Python'] Example No4
["%3.2f%%,0x%x,0x%02X"% (65.5687,10,16)] where:
[%3.2f%%] means to output a floating-point number, [integer part + decimal point + decimal part] a total of 3 effective digits, of which the effective digit of the decimal part is 2 digits. Fill in the insufficient digits with spaces. Among them, %% is the translation output% number. If it is [%03.2f%%] then the insufficient number of digits is filled with 0 [0x%x] According to the hexadecimal output 10, corresponding to a in the hexadecimal number Example No5
["%0-10.2f%%,0x%x,0x%02X"% (65.5687,10,16)] where [%0-10.2f%%] in [-] the negative sign means right-aligned, not written by default Left aligned
format string formatting
Syntax: "{}{xxx}".format(*args,**kwargs)->str
args is a positional parameter, a tuple kwargs is a keyword parameter, is a dictionary {} curly braces are placeholders, indicating that the parameters are matched in order, {n} indicates that the value corresponding to the positional parameter args[n] {xxx} Where xxx is the keyword name, which means searching for the parameter corresponding to the same name in the keyword parameter kwargs. {{}} means printing curly braces (note: double symbols indicate translation output) Position parameters:
Replace the placeholders of the previous format string with positional parameters in the order of position. For example: ["{}:{}".format("192.168.61.100",8888)] keyword parameters or named parameters
Position parameters are matched by sequence number, keyword parameters are matched by name. For example: [{server}{1}:{0}.format(8888,"192.168.61.100",server=”xdd”)] Access element:
For example: ["{0[0]}.{0[1]}".format(('xdd','com'))] Object attribute access
For example: ["({p1.x},{p1.y})".format(p1=p)] Align
For example: ["{0}{1}={2:< 3}".format(3,2,32)] where [{2:< 3}] means the content of the output array with subscript 2 . The output character length is 3 characters long, if it is not enough, fill it with spaces. <Less than sign indicates left-justified output, centered
For example: [{:*^30}.format('centered')]
Means to display the centerd word in the center. The display length is 30 characters. If it is not enough, replace with *asterisk [^] to indicate centered.
For example: ["int:{0:d}; hex:{0:x}; oct:{0:o}; bin:{0:b}".format(50)]
[{0:d}] means output in decimal digits [{0:x}] means output in hexadecimal digits [{0:o}] means output in octal numbers [{0:b}] means in binary In digital output [{0:#b}], # represents when outputting a number, bring the corresponding symbol of refined number, for example:
Among them: 192.168.0.1 name: ipv4 address in dotted four-segment decimal notation [.format(*octets)] where * means, the octets list is converted into elements of corresponding length
Recommended Posts