Data types and operations for Python

Source: Internet
Author: User

Brief introduction to several simple data types of Python and how to use them


Strings are immutable data types and can be manipulated with a variety of built-in methods.

Creating a string is a value that assigns a string to a variable. Strings are usually created in quotation marks.

' My name is Jeff '  "my name is Jeff" and "My name is Jeff,i ' m oldboy. " "

string slices

' My name is Jeff ' Print (tell[0]) Print (Tell[:7]) Print (tell[:7]+'\tfrank') run result mmy namemy name    Frank

Using the Split method

 "" Print (Tell.split (' a ')) run result [' My n ' '  ']

String formatted output

Print ('My name is%s'percent ('Jeff' is Jeff
Print ('my name is {name}'. Format (name='Jeff' )   is Jeff

Built-in methods for strings

1.capitalize (the entire string is capitalized, all the others are changed to lowercase)

2.upper (whole string all uppercase) lower (all lowercase) (Specify width and fill character)

 "" Print ( ()) Run result ********** My name is Jeff *****************

4.count (number of characters in a range)

"" Print (Tell.count (' m ', 0,5)) Run result 1

5.encode (coded)

6.endswith (end with a character, string)

" My name is Jeff " Print (Tell.endswith ("ff")) Run result ture

7.expandtabs (Choose the width of the tab)

8.find (the position of the index character, no return value is-1) index (same as find, but he does not check the error) RFind (right-to-Zocha with Find) Rindex (right-to-left index value returned)

9.format (formatted output) Format_map (formatted output, storing KV data in dictionary form)

people={    'name':['Frank','Caroline','Jeff'],    ' Age':[' at',' A'],}Print("My name is {name[2]},i am {age[0]} years old!". Format_map (people)) run result my name isJeff,i am years old!

10.isalnum (whether it is a combination of numbers and letters) Isalpha (whether it is a combination of letters) Isdecimal (whether a decimal positive integer) isdigit (True integer) Isdentifier (whether it is an identifier in Python) islower (judging if the string letter is not all lowercase) isnumeric (is not a number, Whether Chinese or other as long as the number can be judged) isprintable (printable) isspace (whether all spaces, TAB/R, etc.) Istitle (whether all characters are capitalized) The return value is a bool value

11.join (generates a new string with the specified character connection)

" My name is Jeff " Print ('='. Join (Tell) ') running result m=y= =n=a=m=e= =i=s= =j=e=f=f

12.ljust and Rjust Specify character width padding, similar to center

" My name is Jeff " Print (Tell.ljust (+,'=')) Print (Tell.rjust (+,'=')) operation result My name is Jeff==========my name is Jeff

13.lstrip,rstrip,strip go back and forth blank \ r \ n


" ABCDE "  "12345""My name is Jeff"= Tell . Maketrans (Intab, Outtab) Print (Tell.translate (trantab)) Run result my n1m5 is j5ff

15.partition (Specify separator character, return a tuple) rpartition (split right-to-left, split only once, if no specified character returns a tuple preceded by two empty strings) split (specify character split, You can specify the number of split times to delete the specified character by default space split) Rsplit (same split just right-to-left)

16.replace (Specifies the number of characters to be replaced with new characters)

17.splitlines (Converts a string to a list)

18.startswith (whether it is a string or a character start)

19.swapcase (case swap)

20.zfill (similar to center, display on the right of insufficient width 0)

Integral type and long integer type

An integer is a numeric value that contains no fractional parts, and the format is "int". A long integer is similar to an integral type except that the number is larger and the format is "type". And the long integer only exists in the Python2, the value range of the 32-bit machine is -2**31~2**31-1, and the value is -2**63~2**63-1 on the 64-bit machine. There is no distinction between integral type and long integer in Python3, only integral type.

Floating point Type

We can simply think of floating-point types as decimals. The format type is "type". Floating-point types are often used in scientific notation, except as fractional outputs.

A=1.23e10b=1.23e10print(a)print (b)print(type (a))  Print(type (b)) output 12300000000.012300000000.0<class'float  '><class'float'>

There are only two return values for the bool type: TRUE and false.

Logical operation:

1. With Operation: and (two both are true, the result is true)

2. Or: or (true if one is true)

3. Non: Not (turns true to false and false to true)

Short-circuit Operation:

Boolean types can also be logically operated with other data types, and Python 0, empty string, None, empty list, empty dictionary, and so on are false, and other numeric and non-empty strings are true.

1. When calculating A and B, if A is true, the result of the calculation depends on B, then B is returned, and if A is false, a is returned directly.

2. When a or B is calculated, if a is true, a is returned directly, or B is returned.

The bool type can also be used as 0 and 1 of the integer type.

Print (true+13)    # true is 1 Print (false+13)   # false to 0 Output Results 1413

A list consists of a series of elements arranged in a particular order. In Python, the list is represented by square brackets, and the elements are separated by commas, with the format type "list".

The built-in methods of the list are:

1.append (add an element at the end of the list) insert (also add element, but can specify insert location by country Index)

2.count (number of elements)

3.clear (Empty list)

4.copy (copy list)

name = ['Jeff','Frank', 1,{'Xixi':'Sabi'},[3,4]]NAME_CP=name.copy ()Print(NAME_CP) name[0]='Tom'name[2]= 7Print(name)Print(NAME_CP) run result ['Jeff','Frank', 1, {'Xixi':'Sabi'}, [3, 4]]['Tom','Frank', 7, {'Xixi':'Sabi'}, [3, 4]]['Jeff','Frank', 1, {'Xixi':'Sabi'}, [3, 4]]

Note: Changing the value in the element name.copy in the list name also varies. But by changing the list value in the list name, the Name.copy list value will not become. Because the list of lists opens up spaces that are immutable (the list itself is a mutable data type) name and Name.copy point to the same address, and the stored values are changed together.

5.deepcopy is similar to copy, but regardless of how the copy original list changes, the list of deepcopy changes with the list, which points to a unified data space.

6.extend (function is used to append multiple values from another sequence at the end of the list, extending the original list with a new list.) )

name = ['Saber','Frank']nameto= ['Mei','Jack']name.extend (Nameto)Print(name) run the result ['Saber','Frank','Mei','Jack']

7.index (finds the index value of the corresponding element, can specify the index range and cannot be found or error)

8.pop (popup element, do not specify the default pop-up last value, index failure will be an error, the value of the popup can be stored in other lists or variables.) Remove (also remove, specify the specific element to remove) del (Invincible removal method)

9.reverse (reverses the elements in the list)

10.sort (sort the list, permanent modification can be passed backwards by reverse=true) sorted (elements similar to sort but not changing the original list)

11.len (View the length of the list)


Similar to a list, except that you cannot make changes. If you want to change the value in a tuple, you can only get rid of the entire tuple.


The collection is not composed of elements, the order of printing is also unordered, but there are no duplicate elements in the collection, so we often use the set to weight.

We have two sets A and B:

The intersection of A and B is a.intersection (b) or A & B.

The difference between A and B is either a.difference (b) or a-a.

A and B are a.union (b) or a|b.

The inverse difference sets are a.symmetric_difference (b) or a^b with the symmetric difference set (and the set minus the intersection).

Merge to A.update (b), a.difference_update (b) Differential set and assign to a set

Delete element can be discard (element) or remove (element), pop () is randomly delete an element.

Note: Set is a mutable data type, but the element inside the set must be an immutable data type.


In Python, a dictionary is a series of key-value pairs, each of which corresponds to a value, and the keys can be numbers, strings, lists, and dictionaries. Any Python object can be used as a dictionary value.

The built-in methods commonly used in dictionaries are:

Keys (remove the key from the dictionary)

Values (remove value from dictionary)

Clear (Clears all key-value pairs)

Copy (same as list)

Fromkeys (Create a new list all values are the same value)

Key = (1,2,3,4,5) Value= ('a','b','C','D','e')Print(Dict.fromkeys (key,value)) Run result {1: ('a','b','C','D','e'), 2: ('a','b','C','D','e'), 3: ('a','b','C','D','e'), 4: ('a','b','C','D','e'), 5: ('a','b','C','D','e')}

Get (Find a way to find the object that returns none)

Item (return key value pair)

Pop (specify key to eject this key value pair)

Popitem (popup Last key value pair returned to the tuple without error)

Update (adds a new dictionary to the original dictionary, overwriting the original value if the original dictionary contains the key)

SetDefault (K,V) If the key is in the dictionary, the value of the key is returned, if it is not in the dictionary, the key is inserted into the dictionary, and value is returned, and the default value bit is None.


All the characters designators to the storage unit are bytes types.

Here is a brief summary of the common data types in Python and some built-in usage methods, so that you could summarize the learning of Python in the future.

Data types and operations for Python

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: 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.