3. Supplement of strings, lists, tuples, dictionaries, and collections, and string dictionaries

Source: Internet
Author: User

3. Supplement of strings, lists, tuples, dictionaries, and collections, and string dictionaries
Related:

  • String
  • List
  • Dictionary
  • Set

Additional:

Many python compilers provide code complementing functions and prompt functions when entering parameters.

String

 

1. Common functions:
The string is an immutable object, and the string method does not change the data of the original string.
S = "hEllo world! \ T "print (" s. capitalize (): ", s. capitalize () # format the title print ("s. center (20, '-'): ", s. center (20, '-') # Fill the string in the center, fill in the element to specify characters, the total number of characters is specified print ("s. count ('l'): ", s. count ('l') # count the number of occurrences of a string print ("s. endswith: ", s. endswith ('d! ') # Judge whether the string is d! Print ("s. find ('O'): ", s. find ('O') # find the specified Element and return its index print ("s. index ('O'): ", s. index ('O') # Find the specified Element and return its index sep = 'abc' print ("s. join (sep): ", s. join (sep) # Insert the original character s to print ("s. lower (): ", s. lower () # convert all to lowercase print ("s. replace ('l', 'J', 1): ", s. replace ('l', 'J', 1) # replace the specified character. The last one is to replace the Count print ("s. split (): ", s. split () # cut the string. The cut character is the specified print ("s. strip (): ", s. strip () # Remove left and right space elements. rstrip removes only the right side, and lstrip removes only the right side of print ("s. upper (): ", s. upper () # convert all to uppercase "is series: isdigit ()-" whether it is a number, isalnum ()-"whether it is a letter or a number, isalpha () -whether it is an English letter islower ()-whether it is all lowercase ,"""

Appeal code result:

s.capitalize():  hello world!     s.center(20,'-'): -- hEllo world!     ---s.count('l'): 3s.endswith: Falses.find('o'): 5s.index('o'): 5s.join(sep): A hEllo world!     B hEllo world!     Cs.lower():  hello world!     s.replace('l','j',1):  hEjlo world!     s.split(): ['hEllo', 'world!']s.strip(): hEllo world!s.upper():  HELLO WORLD!

 

2. String formatting: python string formatting-this parameter seems to give a good result
>>> s="%d is 250">>> s%250'250 is 250'>>> b = "%(name)+10s————————%(age)-10d————————"%{'name':'xx','age':20}>>> print(b)        xx————————20        ————————>>> s="{:d} is a 250">>> s.format(250)'250 is a 250'>>> a1 = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%},{:c}".format(15, 15, 15, 15, 15, 15.87623,65)>>> print(a1)numbers: 1111,17,15,f,F, 1587.623000%,A>>> s="{} {} 250">>> s.format(250,"500-250")'250 500-250 250'>>> s.format(250,"500-250")'250 500-250 250'

 

3. original string:

Cause: to avoid excessive use of \ escape, when the string format is r "string", all characters in it are considered as characters, for example, \ n is no longer the original line feed.

>>> print("a\tb")a    b>>> print(r"a\tb")a\tb

However, the string cannot be processed. If the end is \:

>>> print(r"c:\a\b")c:\a\b>>> print(r"c:\a\b\")      SyntaxError: EOL while scanning string literal>>> print(r"c:\a\b\\")c:\a\b\\>>> print(r"c:\a\b"+"\\")c:\a\b\

In this case, it is best to use String concatenation for processing.

List

 

1. Common functions:
Print ("query ". center (20, '-') list_find = ['apple', 'Banana ', 'pen, 3] # search for the subscript print (list_find.index ('apple') of a specified Element) # search for the number of existing print (list_find.count ("apple") print ("add ". center (20, '-') list_add = ['apple', 'bana'] # append an element to the end of list_add.append ("Hami melon") print (list_add) # insert an element to the specified position list_add.insert (0, "apple") print (list_add) print ("delete ". center (20, '-') list_del = [1, 2, 3, 4, 5, 6, 7, 8, 9] # retrieve elements from the List (delete). pop can be set as a parameter, the parameter is the subscript list_del.pop () print (list_del) of the deletion element # Delete the element list_del.remove (4) print (list_del) of the specified element name) # Delete the corresponding element space del list_del [0] print (list_del) print ("other ". center (20, '-') list_test4 = ['A', 'B', 'D', 'C'] list_test5 = [1, 2, 3, 4] # extended list list_test5.extend (list_test4) print (list_test5) # Sort the list list_test4.sort () print (list_test4) # Note: py3 cannot sort different element types # reverse list list_test5.reverse () print (list_test5)

 

The code execution result is as follows:

--------- Query ---------- 01 --------- add ---------- ['apple', 'Banana ', 'cantalou'] ['apple', 'apple', 'Banana ', 'cantalanga'] --------- Delete ---------- [1, 2, 3, 4, 5, 6, 7, 8] [1, 2, 3, 5, 6, 7, 8] [2, 3, 5, 6, 7, 8] --------- others --------- [1, 2, 3, 4, 'A', 'B', 'D ', 'C'] ['A', 'B', 'C', 'D'] ['C', 'D', 'B', 'A', 'A', 4, 3, 2, 1]
2. List generation:
# Exp = expression # process: 1. iterate every element in iterable; #2. each iteration first assigns the result to iter_var, and then obtains a new calculated value through exp; #3. finally, all the calculated values obtained through exp are returned in the form of a new list. # [Exp for iter_var in iterable] print ("1. [exp for iter_var in iterable] ") list1 = [I for I in range (10)] print (list1) list2 = [I * I for I in range (10, 20)] print (list2) print ("\ n") # [exp for iter_var in iterable if_exp] print ("2. [exp for iter_var in iterable if_exp] ") list3 = [I for I in range (10) if I % 2 = 0] print (list3) print (" \ n ") # [exp for iter_var_A in iterable_A for iter_var_ B in iterable_ B] print ("3. [exp for iter_var_A in iterable_A for iter_var_ B in iterable_ B] ") list4 = [x * y for x in range (5) for y in range (5)] print (list4) print ("\ n ")

The code execution result is as follows:

1.[exp for iter_var in iterable][0, 1, 2, 3, 4, 5, 6, 7, 8, 9][100, 121, 144, 169, 196, 225, 256, 289, 324, 361]2.[exp for iter_var in iterable if_exp][0, 2, 4, 6, 8]3.[exp for iter_var_A in iterable_A for iter_var_B in iterable_B][0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 2, 4, 6, 8, 0, 3, 6, 9, 12, 0, 4, 8, 12, 16]

 

Dictionary

 

1. Common functions:
D1 = {1: "apple", "sprite": "Sydney"} d1.clear () # Clear the dictionary print (d1) d1 = {1: "apple", "sprite ": "Sydney"} print (d1.get (1) # obtain the print (d1.get (3) Result of the specified dictionary key # If the key does not exist, return Noneprint (d1.items ()) # obtain all key-value pairs of the dictionary print (d1.keys () # obtain the dictionary key print (d1.values () # obtain the dictionary value print (d1.pop (1 )) # print (d1.popitem () # print (d1) d1 = {1: "apple", "sprite ": "Sydney"} d1.update ({1: 'apple', 3: 'pen '}) # update result, same key name updated, new key name added result print (d1)

The code execution result is as follows:

{} Apple Nonedict_items ([(1, 'apple'), ('sprid', 'sydney ')]) dict_keys ([1, 'sprid']) dict_values (['apple ', 'sydney']) apple ('sprite ', 'sydney') {}{ 1: 'apple', 'sprite ': 'sydney ', 3: 'pen '}

 

Set

 

1. Common functions:
S1 = set (['A', 'B', 'C']) print (s1.pop () # randomly delete an element in the set, after an element is obtained, the returned value is print (s1) s3 = {'A', 'D'} s1.update (s3) # update print (s1) s1.add ('F ') # add element print (s1) s1.clear () # Clear s1 = set (['A', 'B', 'C', 'F']) print (s1) s1.remove ('A') # Delete the target element. If no element exists in the Set, the following error occurs: print (s1) s1.discard ('G') # If no element exists in the Set, no error is returned; if an element exists, print (s1) B = {'A', 'B', 'G'} print ("s1.difference (B)") print (s1.difference (B) is deleted )) # retrieve the elements in s and B in the set and return the print ("s1.interscetion (B)") print (s1.intersection (B) # intersection of the elements, returns the print ("s1.issubset (B)") (s1.issubset (B) set composed of elements in s and B )) # determine if s is a subset of B print ("s1.issuperset (B)") print (s1.issuperset (B) # determine if s is a parent set of B print ("s1.20.ric _ difference (B) ") print (s1.equalric _ difference (B) # Get the difference set and create a new set print (" s1.union (B) ") print (s1.union (B )) # Union set print ("symmetric_difference_update") print (s1) s1.equalric _ difference_update (B) # print (s1) without return value "xxxx_update will overwrite the s1 value, for example: s1.symmetric _ difference_update (): The result of resolving ric_difference will overwrite the value of s1 """

 

The above Code results:

a{'c', 'b'}{'c', 'b', 'd', 'a'}{'c', 'b', 'd', 'f', 'a'}{'a', 'c', 'b', 'f'}{'c', 'b', 'f'}{'c', 'b', 'f'}s1.difference(b){'c', 'f'}s1.interscetion(b){'b'}s1.issubset(b)Falses1.issuperset(b)Falses1.symmetric_difference(b){'a', 'g', 'c', 'f'}s1.union(b){'g', 'c', 'b', 'f', 'a'}symmetric_difference_update{'c', 'b', 'f'}None{'g', 'c', 'f', 'a'}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.