Python lists, dictionaries, tuples, strings, common functions

Source: Internet
Author: User
Tags iterable shallow copy

Airline tickets. List method

1.ls.extend (object)

Inserting each element in the object into the list LS, object can be a string, a tuple and a list (the string "ABC" contains 3 tuples), which is equivalent to the combination of LS and object. Note: If object is an integral type, it must be passed in as a list, and cannot be passed in as an integer or tuple

2.ls.append (object)

Insert object as a whole into LS Finally, object can be string, tuple, list and dictionary

3.ls.insert (Index, object)

Inserts an object as a whole into the index position specified by LS, where object can be a string, a tuple, a list, and a dictionary

4.ls.pop ([index])

Removes the element at the specified index location, returns the element that was deleted, and, if the argument is empty, deletes the element at the last index position by default. Note: There is a return value

5.ls.remove (value)

Deletes the specified element. Note: value is the values inside the sequence, not the index

6.ls.reverse ()

To reverse-arrange elements in a list

7.ls.sort (Cmp=none, Key=none, Reverse=false)

By default, the elements in the list are sorted in ascending order and can be set to descending by the reverse parameter

Two. Lists, methods common to tuples

1.ls.count (value)

Number of element value in the statistics list

2.ls.index (value, [Start, [stop]])

Returns the index position of the specified element in the list, which can be set by the start and stop parameters. Note: An exception is reported if it does not exist

Three. Dictionary methods

1.dic.clear ()

Delete all items in a dictionary

2.dic.fromkeys (S[,v])

Creates a new dictionary with a key of S, a value of V, and if S is a long string, the key returned is every character in the string, and the value repeats. Note: The entries in the DIC dictionary do not change

3.dic.get (K[,d])

Gets the value of the specified key in the dictionary, or none if K does not belong to a key in the dictionary. Note: equivalent to dic[k], but dic[k] if K does not belong to a key in the dictionary, the exception is reported

4.dic.setdefault (K[,d])

Similar to the Dit.get (k,d) method, if K belongs to a key in the dictionary, the corresponding value is returned, otherwise the key value is inserted into the dictionary

5.dic.has_key (k)

Returns whether the dictionary contains the key k, and the return value is true and False

6.dic.items ()

Returns the key values in the dictionary as a list, with each pair of key values stored in a tuple

7.dic.keys ()

Returns a dictionary of all keys in the form of a list

8.dic.values ()

Returns all values in the dictionary as a list (values)

9.dic.iteritems ()

A key-value iterator, typically used for a for loop

10.dic.iterkeys ()

Key iterators, typically used for a for loop

11.dic.itervaleus ()

Value iterators, typically used for a for loop

12.dic.viewitems ()

Returns a view of the key values in the dictionary, a single key-value pair is stored in a tuple, all key-value pairs are in the list, the return type is Dict_items, and can be used as an iteration for a for loop

13.dic.viewkeys ()

Returns a view of the keys in a dictionary, a single key in a tuple, all keys in a list, a return type of dict_items, or as an iteration for a for loop

14.dic.viewvalues ()

Returns a view of values in a dictionary, a single value in a tuple, all the values in a list, a return type of dict_items, or as an iteration for a for loop

15.dic.pop (K[,d])

Deletes the value of the specified key in the dictionary and returns the corresponding value of the deleted key

16.dic.popitem ()

Randomly deletes a key-value pair and returns the corresponding value of the deleted key without passing parameters to the method

17.dic.update ([E,]**f)

Update the key value pairs in the dictionary e to dic, equivalent to the list of DIC and List E merged and updated to the list dic

18.dic.copy ()

Shallow copy: Copies only the parent object in the dictionary and takes a reference to the child object. Changing the contents of a child object affects the copied and copied dictionaries.

Cases:

1 a ={' name ': ' Ali ', ' age ': ' Score ': [10,20,30]}2     B = a.copy () 3     b[' name '] = ' bai ' 4     b[' score '].remove (20) 5     print B6     print a

Output Result:

{' Age ': ' Score ': [ten], ' name ': ' Bai '} {' Age ': +, ' score ': [Ten, +], ' name ': ' Ali '}

Four. String method # Letter Processing

1.string.capitalize ()

Returns a string, with the first letter of the string capitalized, and the other letter lowercase

2.string.title ()

Returns a string, with the first letter of the string capitalized, and the other letter lowercase

3.string.swapcase ()

Used to convert the uppercase and lowercase characters of a string, lower case letters to lower letters

4.string.upper ()

To capitalize all strings

5.string.lower ()

Convert all strings to lowercase

#去除空格或者指定字符串

1.string.strip ([string])

Remove the string from the end of the string without a parameter and remove the space by default

2.string.lstrip ([string])

Strips the left string of the string without parameters, removing the space by default

3.string.rstrip ([string])

Remove strings to the right of the string without parameters, remove whitespace by default

#格式化对齐

1.string.center (width[, Fillchar])

Returns the center alignment of the original string, width of the total length, with a character fillchar padding on both sides, and returns the original string if the specified length is less than the length of the original string. Note: If the Fillchar exceeds 1 lengths or is not a string or is a kanji, an exception is reported

2.string.ljust (width[, Fillchar])

Returns the original string left-aligned and fills the new string with a space of the specified length, or returns the original string if the specified length is less than the length of the original string. Note: If the Fillchar exceeds 1 lengths or is not a string or is a kanji, an exception is reported

3.string.rjust (width[, Fillchar])

Returns the original string right-aligned and fills a new string of the specified length with a space, or returns the original string if the specified length is less than the length of the string. Note: If the Fillchar exceeds 1 lengths or is not a string or is a kanji, an exception is reported

4.string.zfill ()

Returns a string of the specified length, the original string is right-aligned, and the front padding 0

#替换

1.string.replace (old, new[, Count])

Replace old characters with new characters, specify the number of replacements, replace all by default

2.string.expandtabs ([n])

Converts a string (tab symbol) \ t to n spaces

#字符串搜索

1.string.find (Sub [, Start [, end]])

Returns the index position of the first occurrence of the sub string, which can be set by the start and stop parameters, or 1 if a sub is not found

2.string.rfind (Sub [, Start [, end]])

Returns the index position of the last occurrence of the sub string, or 1 if no match is found, which can be set by the start and stop parameters

3.string.index (Sub [, Start [, end]])

Similar to the String.find () method. Note: An exception is reported when a sub is not found

4.string.rindex (Sub [, Start [, end]])

Similar to the String.rfind () method. Note: An exception is reported when a sub is not found

#字符串分割

1.string.split ([Sep [, Maxsplit]])

Used to split the string according to the specified delimiter, without delimiters, the result is saved as a list, and when no Sep is specified, a space is used as the delimiter by default

2.string.partition (Sep)

Used to split the string according to the specified delimiter, where the split point is the first occurrence of Sep, and contains a delimiter, the result is stored as a tuple, and fixed to 3 elements, if Sep does not exist in the string, then the next 2 elements are empty

3.string.rpartiton ()

Used to split the string according to the specified delimiter, the split point is the last occurrence of Sep, and contains a delimiter, the result is stored as a tuple, and fixed to 3 elements, if Sep does not exist in the string, then the first 2 elements are empty

#字符串判断

1.string.isupper ()

Returns whether the string is all uppercase-and true/false

2.string.islower ()

Returns whether the string is all lowercase--and True/false

3.string.isdigit ()

Returns whether the string contains only numbers--true/false

4.string.isalpha ()

Returns whether the string contains only letters---True/false

5.string.isalnum ()

Returns whether the string contains only letters or numbers--true/false

6.string.isspace ()

Returns whether the string contains only spaces (tab also counts as spaces)-True/false

7.string.istitle ()

Returns whether the first letter in a string is capitalized--true/false

8.string.startswith (prefix[, start[, end]])

Returns whether the string starts with a string and can be set by the start and stop parameters

9.string.endswith (suffix[, start[, end]])

Returns whether a string ends with a string you can set the search scope by using the start and stop parameters

#其它

1.string.count (sub[, start[, end]])

Count the number of subsets in a string, you can set the search scope by the start and stop parameters

2.len (String)

Gets the length of the string

3.list (String)

String Goto List

4.string.join (iterable)

A list-to-string that is used to generate a new string for the elements in the sequence with the specified character string. Note: Iterable can only be a string type, otherwise an exception will be reported

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

Encodes a string in the encoded format specified by encoding

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

Decode string, error default report ValueError unless errors is ignore or replace

7.string.translate (table [, Deletechars])

Converts the character of a string according to the table given by the parameter table (containing 256 characters), and the character to be filtered out into the Deletechars parameter

Cases:

1 #!/usr/bin/python2 #coding: utf83 import String4 intab = "ABCD" 5 Outtab = "1234" 6 tab = String.maketrans (intab,outtab) 7 s TRS = "abcd### #abcdefg" 8 Print strs.translate (tab) 9 Print strs.translate (tab, ' AB ')

Output Result:

1234### #1234efg34 # # # #34efg

8.string.format (*args, **kwargs)

It replaces% with {} and:

"Mapping" Example:

By location

1 print ' {0}#{1} '. Format (' YYY ', ten) 2 print (' {} ' + ' # ' + ' {} '). Format (' YYY ', ' NNN ') 3 print ' {1}#{0}#{1} '. Format (' YYY ', ' NNN ‘)

Output Result:

yyy#10yyy#nnnnnn#yyy#nnn

by keyword parameter

1 str1 = ' {name} ' + ' is ' + ' {age} ' 2 print Str1.format (name= ' Ali ', age=20)

Output Result:

Ali is 20

Through object properties

1 class students (): 2     def __init__ (self,name,age): 3         self.name,self.age = name,age4 5     def __str__ (self): 6         str1 = ' {self.name} ' + ' is ' + ' {self.age} ' 7         return Str1.format (self=self) 8 9 Print str (Students ("Ali", 20))

Output Result:

Ali is 20

by subscript

1 name = [' Ali ', ' Baidu ']2 age = [10,20]3 str1 = ' {0[0]},{0[1]} ' + ' is ' + ' {1[0]},{1[1]} ' 4 print Str1.format (name,age)

Output Result:

Ali,baidare 10,20

With these convenient "mapping" methods, we have a lazy weapon. Basic Python knowledge tells us that list and tuple can be "broken" into normal parameters to the function, and dict can be broken into the keyword parameters to the function (through and *). So you can easily pass a list/tuple/dict to the Format function. Very flexible.

Format qualifier

It has a rich "format qualifier" (syntax is {} with: number)

For example: Fill and align

Padding is used in conjunction with alignment
^, <, > center, Align Left, right, back with width
: The filled character after the number, only one character, not specified by default is filled with spaces, the effect is equivalent to String functions Center,ljust and Rjust.

Cases:

1 print ' {: a^10} '. Format (' 123 ') 2 print ' 123 '. Center (+, ' a ') 3 print ' {: a<10} '. Format (' 123 ') 4 print ' 123 '. Ljust (' A ') 5 print ' {: a>10} '. Format (' 123 ') 6 print ' 123 '. Rjust (' a ')

Output Result:

Aaa123aaaaaaa123aaaa123aaaaaaa123aaaaaaaaaaaaaa123aaaaaaa123

Accuracy and type

Accuracy is often used in conjunction with Type F

1 print ' {:. 2f} '. Format (123.456)

Output Result:

123.46

Where. 2 represents a precision of 2 length, and F represents a float type.

Delimiter, the number can also be used to make the amount of thousands separator.

1 print ' {:,} '. Format (123456789)

Output Result:

123,456,789

Other types

Mainly in the system of B, D, O, X are binary, decimal, octal, hexadecimal.

1 print ' {: b} '. Format (+) 2 print ' {:d} '. Format (+) 3 print ' {: o} '. Format (+) 4 print ' {: x} '. Format (17)

Output Result:

10001172111

Python lists, dictionaries, tuples, strings, common functions

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.