In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "what are the commonly used string functions in python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Array
Print (a) # how to create a listL1 = [] print (type (L1)) print (L1) L2 = [1, 2, 3, 5, 9, 0] print (L2) # add L2.append (11) # insert into the last value print (L2) # add to the specified position, insert (insert into what data) other data will move one position to the right # each value in list The location they are in is called the subscript. The id starts from left to right and starts from 0. L2.insert (2Magne13) print (L2) # deletion # remove is deleted through the value, and the first value found from left to right is deleted # if the value does not exist Report exception L2.remove (0) print ("=") print (L2) print (L2.pop (4)) print (L2) # change L2 [1] = '111 query # look up print (L2 [1]) print (L2 [3]) print (L2 [6]) # traversal list data query for i in L2:print ("current element:", I)
two。 Array common function
Len (list)
Number of list elements
Max (list)
Returns the maximum value of the list element
Min (list)
Returns the minimum value of a list element
List (seq)
Convert tuples to lists
List.append (obj)
Add a new object at the end of the list
List.count (obj)
Count the number of times an element appears in the list
List.extend (seq)
Append multiple values from another sequence at the end of the list at once (extend the original list with the new list)
List.index (obj)
Find out the index position of the first match of a value from the list
List.insert (index, obj)
Insert objects into the list
List.pop ([index=-1])
Removes an element from the list (the default last element) and returns the value of that element
List.remove (obj)
Remove the first occurrence of a value in the list
List.reverse ()
Elements in reverse list
List.sort (key=None, reverse=False)
Sort the original list
List.clear ()
Clear the list
List.copy ()
Copy list
3. Common string function
Capitalize ()
Converts the first character of a string to uppercase
Center (width, fillchar)
Returns a string with the specified width centered by width. Fillchar is a padded character and defaults to a space.
Count (str, beg= 0 (string))
Returns the number of str occurrences in string, or the number of str occurrences within the specified range if specified by beg or end
Bytes.decode (encoding= "utf-8", errors= "strict")
There is no decode method in Python3, but we can use the decode () method of the bytes object to decode the given bytes object, which can be encoded and returned by str.encode ().
Encode (encoding='UTF-8',errors='strict')
Encode a string in the encoding format specified by encoding. If there is an error, an exception of ValueError is reported by default, unless errors specifies' ignore' or 'replace'.
Endswith (suffix, beg=0, end=len (string))
Check whether the string ends with obj, and if beg or end is specified, check whether the specified range ends with obj. If so, return True, otherwise return False.
Expandtabs (tabsize=8)
Convert the tab symbol in the string string to spaces, and the default number of spaces for the tab symbol is 8.
Find (str, beg=0, end=len (string))
Check whether str is contained in a string, if you specify a range of beg and end, check whether it is included in the specified range, and return-1 if it contains the index value that returns the start.
Index (str, beg=0, end=len (string))
Just like the find () method, except that an exception is reported if the str is not in the string.
Isalnum ()
Return True if the string has at least one character and all characters are letters or numbers, otherwise return False
Isalpha ()
Return True if the string has at least one character and all characters are letters or Chinese characters, otherwise return False
Isdigit ()
Return True if the string contains only numbers, otherwise return False..
Islower ()
If the string contains at least one case-sensitive character, and all these (case-sensitive) characters are lowercase, True is returned, otherwise False is returned
Isnumeric ()
Returns True if the string contains only numeric characters, otherwise returns False
Isspace ()
Returns True if the string contains only whitespace, or False.
Istitle ()
Returns True if the string is themed (see title ()), otherwise returns False
Isupper ()
Returns True if the string contains at least one case-sensitive character, and all these (case-sensitive) characters are uppercase, otherwise returns False
Join (seq)
Merges all elements (string representation of) in seq into a new string with the specified string as the delimiter
Len (string)
Returns the string length
Ljust (width [, fillchar])
Returns a new string that is left-aligned and populated with fillchar to the length width. Fillchar defaults to spaces.
Lower ()
Converts all uppercase characters in a string to lowercase.
Lstrip ()
Truncates the space to the left of the string or the specified character.
Maketrans ()
Create a conversion table for character mapping. for the easiest way to accept two parameters, the first parameter is a string, which represents the character to be converted, and the second parameter is the string that represents the target of the conversion.
Max (str)
Returns the largest letter in the string str.
Min (str)
Returns the smallest letter in the string str.
Replace (old, new [, max])
Replace the old in the string with new, or no more than max times if specified by max.
Rfind (str, beg=0,end=len (string))
Similar to the find () function, but starting from the right.
Rindex (str, beg=0, end=len (string))
Similar to index (), but starting on the right.
Rjust (width, [, fillchar])
Returns a new string that is right-aligned and populated with fillchar (the default space) to the length width
Rstrip ()
Removes the space at the end of a string.
Split (str= "", num=string.count (str))
Use str as the delimiter to intercept strings. If num has a specified value, only num+1 substrings are intercepted.
Splitlines ([keepends])
A list containing lines as elements is returned, separated by lines ('\ r','\ r\ n',\ n'). If the parameter keepends is False, there is no newline character, if it is True, the newline character is retained.
Startswith (substr, beg=0,end=len (string))
Checks whether the string begins with the specified substring substr, returns True if so, returns False otherwise. If beg and end specify values, they are checked within the specified range.
Strip ([chars])
Execute lstrip () and rstrip () on the string
Swapcase ()
Convert uppercase to lowercase and lowercase to uppercase in a string
Title ()
Returns a "titled" string, which means that all words start with uppercase and the rest are lowercase (see istitle ())
Translate (table, deletechars= "")
Convert the characters of string according to the table given by str (containing 256characters), and put the characters to be filtered into the deletechars parameter
Upper ()
Convert lowercase letters in a string to uppercase
Zfill (width)
Returns a string of length width, with the original string aligned to the right, preceded by a 0
Isdecimal ()
Check whether the string contains only decimal characters, and if it returns true, otherwise it returns false.
'1. String constant set 'import stringprint (string.ascii_uppercase) # uppercase letter print (string.ascii_lowercase) # lowercase letter print (string.ascii_letters) # uppercase and lowercase letter print (string.digits) # numeric print (string.punctuation) # symbol set print (string.printable) # input word matching set, including uppercase and lowercase alphanumeric and symbol set' 2. String case conversion 5 'stringed worldletters print (str.capitalize ()) # only the first letter uppercase, Hellojournal worldletters print (str.title ()) # only the first letter of each word is uppercase, Hellojournal Worldword print (str.upper ()) # each letter is uppercase, helloreWorldprint (str.lower ()) # each letter is lowercase, hellomWorldprint (str.swapcase ()) # is case swapped HELLOL WORLDELECTIVE 3. The content of the string determines whether the characters in the 10 'num='123'alp='asd'num_alp='a1s2d'printable=' `~! @ # $%' print (num.isdigit ()) # string are all numbers, whether the characters in the Trueprint (alp.isalpha ()) # string are all letters, and whether the characters in the Trueprint (num_alp.isalnum ()) # string are all letters and numbers Whether the characters in the Trueprint (printable.isprintable ()) # string are all input characters, whether the characters in the Trueprint (num.isnumeric ()) # string are all numbers, whether the characters in the Trueprint (alp.islower ()) # string are all lowercase letters, and whether the characters in the Trueprint (num_alp.isupper ()) # string are all uppercase letters. The characters in the Falseprint (alp.istitle ()) # string are shaped like whether the characters in the title Hello World,Falseprint (''. Isspace ()) # string are all spaces, and whether the characters in the Trueprint ('ha '.isascii ()) # string can be represented by ascll codes. Chinese characters are encoded by Unicode, so they are False'4. Fill the string with 'str='Welcome'print (str.center (13 lemons)) # * Welcome***print (str.ljust (10 lemons)) # Welcome+++print (str.rjust (10) #-Welcomeprint (str.zfill (10)) # 000Welcomeprint ('-100'.zfill (10)) #-000000100print ('+ 100'.zfill (10)) # + 000000100R5. If there is a substring in 'str='awasdhiwhhihuasd~hjdsasdihfi'print (str.index (' asd')) # str, the index value of the self-paid index will be returned. If it does not exist, an error try: print (str.index ('aes')) except ValueError as v: print (v) print (str.find (' asd')) # str will be returned if there is a substring. If it does not exist, return-1print (str.find ('aes')) print (str.count (' asd')) # return the number of substrings contained in the string print (str.count ('aes')) # if it does not exist, return 0string 6. The string replaces' stringy characters hellogramme worldview printed (str.replace ('world','python')) # to generate a copy of the replacement character, hello,python! The original string str did not change the print (str) # Hellograd Worldwide worldviews stringency printing awasdhihihuasdcharacters hjdsasdihfights print (str.replace ('asd','ASD',2)) # awASDhiwhhihuASD~hjdsasdihfi'7. The string addition'# join () method is used to generate a new string from the elements in the sequence with the specified character concatenation # usage: str.join (sequence), sequence includes strings, lists, meta-ancestors, collections and dictionaries (dictionaries connect only key), where the elements of lists, meta-ancestors and collections must be strings, otherwise an error lis= will be reported. Print (''.join (lis)) # I am IronManning print (' * '.join ({' 1mm ABCD' 2'})) print ('- '.join (' ABCD')) print ('+ '.join (' axie pr é c') print ('~ '.join ({' axiaxianghuanghuan2}))'8. String pruning'b = "qq-qeasdzxcrtqwe----" print (b.strip ('q')) #-qeasdzxcrtqwe----'9. String cut'b = "this is string example" print (b.split ('')) # slice ['this',' is', 'string']' 9 with a space as a separator. String cutting''partition (sep) cuts a given string into three parts. First, the string sep is searched, the part before sep is a part, sep itself is a part, and the rest as a part is very similar between partition () and rpartition (). The main difference is that when sepsis is not specified in the string, partition () is divided into three parts, string, blank, blank rpartition () is divided into three parts White space, string''test='haoiugdsgfasdhreiuufufg'print (test.partition (' asd')) # ('haoiugdsgf',' asd', 'hreiuufufg') print (test.partition (' nji')) # ('haoiugdsgfasdhreiuufufg',','') print (test.rpartition ('njj')) # (',', 'haoiugdsgfasdhreiuufufg')
4. Format string
Formatting strings can help us to output what we want, and it is also very convenient to use, mainly in the following forms.
one
two
three
four
five
six
seven
# formatting string
Print ('hello, {0} {1} {2}'. Format ('zhong',' yuan', 'gong')) # formatted by location
Print ('hello, {name}, my name is {self}!'. Format (name = 'tom', self =' sir')) # filled with key
L = ['tom',' sir']
Print ('hello, {l [0]}, my name is {l [1]}!'. Format (l = l) # is populated by the subscript of the array
M = {'name':' tom', 'self':' sir'}
Print ('hello, {m [name]}, my name is {m [self]}!'. Format (m = m) # is filled with key in the dictionary, and the key name is not in quotation marks
The output above is: hello,tom,my name is sirical!
five. String case problem
With regard to the case conversion of English strings, you can use the following functions
one
two
three
four
five
six
seven
eight
nine
# initials capitalized
A = 'hello,zHong yUan GONG GOGG GOGGONGOGONGONGOGOGONGONGONGONGONGONGOGONGOGOG
Print (a.title ())
# all uppercase
Print (a.upper ())
# all lowercase
Print (a.lower ())
# capital the first letter of the first word
Print (a.capitalize ())
The output is as follows:
Hello,Zhong Yuan Gong!!
HELLO,ZHONG YUAN GONG!!
Hello,zhong yuan gong!!
Hello,zhong yuan gong!!
String slicing
one
two
three
four
five
six
seven
D = '123456789'
# get the 3rd to 6th characters
Print (d [2: 6]) # what is entered here is the subscript of the string. When slicing in python, it contains the front and back, just as the output here is the substring of subscript 2-5, not the substring of subscript 2-6.
# get the last 2 characters
Print (d [- 2:])
# reverse the string
Print (d [::-1])
The output is as follows:
3456
eighty-nine
987654321
6. Delete spaces in a string
one
two
three
four
five
six
seven
eight
nine
C = 'hello world!'
# remove the spaces at the beginning and end of the string
Print (c.strip ())
# remove the space on the left side of the string
Print (c.lstrip ())
# remove the space on the right side of the string
Print (c.rstrip ())
# remove all spaces in the string
Print (c.replace (','))
The output is as follows:
Hello world!
Hello world!
Hello world!
Helloworld!!!
Note: do not confuse the strip function with the split function. The former deletes the specified characters in the string and defaults to spaces, while the latter splits the string with specified characters. The default is also spaces.
0x05: change the encoding of a string
Sometimes when we are doing file storage, there will be garbled code. At this time, we will change the code and OK it. The way is as follows
one
two
three
# convert string encoding
E = 'hello,zhongyuan university, you're fine!'
Print (e.encode ('utf-8'))
This is the end of the content of "what are the commonly used string functions in python". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.