Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and beauty - Several data types in Python
Several data types in Python
In general, data types in Python fall into the following categories:

Number (number) includes int, long, float and complex.

String (string) for example: hello, hello, hello.

For example, [1, 2, 3, 4]

Dictionary (for example: {1: Ni Hao, 2: Hello}.

Tuple (tuple) for example: (1, 2,3, abc)

Bool (Boolean type) includes true and false.

Because Python thinks everything is an object, Python doesn't have to actively declare the type of variables like some other high-level languages.

For example, I want to assign a value to the variable I 100, the implementation of python:

i= 100

Implementation of C#:

int I = 100;

These data types are briefly introduced below.

Digital type

Int and long

The reason why you want to put int and long together is because after python3.x, you don't distinguish between int and long, but use int. Python2.x is still different. Let me take Python2.7 as an example:

i = 10

Type (1)

i= 1000000000

Type (1)

So why is 10 an int and100000000 a long? Of course, this is related to the maximum value of int. The maximum value of int type is 23 1- 1, that is, 2 147483647. You can also use sys.maxint

2**3 1- 1

2 147483647L

sys.maxint

2 147483647

Why is the value obtained by the above method a long type (adding' L' after the number indicates a long type)? Because the value of 2**3 1 is 2 147483648, which is long. If you subtract 1 from the long type, the result is still a long, but in fact the maximum value of the int type is 265448.

Type (2 147483647)

Type (2 147483648)

Floating type

Floating-point types are basically the same as those in other languages. Floating-point numbers, to put it bluntly, are numbers with decimal points, and their accuracy is related to machines. For example:

i = 10000. 12 12

Type (1)

Plural number: the type of plural number, the specific meaning and usage can be found in the relevant literature.

String type

There are three ways to declare a string: single quotation mark, double quotation mark and triple quotation mark (including three single quotation marks or three double quotation marks). For example:

str 1 = hello world

str2 = hello world

str3 = hello world

str4 = hello world

Print str 1

hello, world

Print str2

hello, world

Print str3

hello, world

Print str4

hello, world

There are two data types of strings in Python: str type and unicode type. The ASCII encoding adopted by str type means that it cannot represent Chinese. Unicode type adopts Unicode encoding and can represent any character, including Chinese and other languages. Moreover, there is no char type in python like in C language, and even a single character is a string type. The default ASCII encoding of the string. If you want to display a string declared as unicode type, you need to add u or u before the string. For example:

Str 1 = Hello.

Print str 1

hello

Str2 = u China

Print str2

China

Because string operations often occur in projects, and because there are many problems in string coding, let's talk about string coding first. In the process of dealing with python, we often encounter three encodings: ASCII, Unicode and UTF-8. Please refer to this article for details. My simple understanding is that ASCII encoding is suitable for English characters, while Unicode is suitable for non-English characters (such as Chinese and Korean). ), and utf-8 is a storage and transmission format, which re-encodes uncoded characters (encoded in 8 bits). For example:

U = u Korea

Print report # uu6c49

s = u.encode(UTF-8)

Print report # xe6xb 1x89

u2 = s.decode(UTF-8)

Print Report (u2) # uu6c49

Description: Declare unicode string "Han" with unicode encoding "u6c49". After utf-8 encoding conversion, its encoding becomes "xe6xb 1x89".

Summary of coding experience:

1. Declare the encoding format in the python file header;

#-*-encoding: utf-8 -*-

2. Declare the string as unicode, that is, add u or u before the string;

3. For reading and writing files, it is recommended to use codecs.open () instead of the built-in open (), and follow a principle, which format to write and which format to read;

Suppose there are the words "China Chinese Characters" in a text file saved in ANSI format. If you use and print the following code directly on the GUI or IDE (for example, in sublime text or pydev), garbled code or exception will appear, because the codec will read the content according to the encoding format of the text itself:

f = codecs.open(d:/test.txt)

content = f.read()

f.close()

Print content

Please use the following method instead (Chinese only):

#-*-encoding: utf-8 -*-

Import codec

f = codecs.open(d:/test.txt)

content = f.read()

f.close()

In case of instance (content, unicode):

Print content. Coding (utf-8)

Print utf-8

Otherwise:

print content.decode(gbk)。 Encoding (utf-8)

List type

List is a modifiable collection type, and its elements can be basic types such as numbers and strings, or collection objects such as lists, tuples and dictionaries, or even user-defined types. It is defined as follows:

nums =

Type (quantity)

Print numbers

Print list

Print numbers

The first additional item (6)

Print list #

Print number #

Nums.sort (comparison)

Print number #

lstiter = iter(lst)

print

lstiter = iter(lst)

For I(len(lst)) in the range:

Print lstiter.next() # Print in turn.

1

2

three

four

five

Tuple type

A tuple type is a sequence, just like a list. Unlike lists, tuples cannot be modified. The tuple declaration is as follows:

lst = (0, 1,2,2,2)

Lst 1= (Hello,)

Lst2 = (Hello)

Print type(lst 1) # If there is only one element, it should be followed by a comma, otherwise it is str type.

Print type (lst2) #

Dictionary type

A dictionary type is a collection of key-value pairs, similar to a dictionary in C#

dict 1 = {}

Print type(dict 1) # declares an empty dictionary.

Dict2 = {name: kitty, age: 18} # directly declare the dictionary type.

Dict3 = Dict ([ (name, kitty), (age, 18)]) # Use the dict function to convert the list into a dictionary.

Dict4 = Dict (name = kitty, age = 18) # Convert it into a dictionary according to keyword parameters with dict function.

Dict5 = {}。 Fromkeys([name, age]) # Use the fromkeys function to generate a dictionary from the list of key values, and the corresponding value is None {age: None, name: None}.

The basic operation method of the dictionary:

# Add elements

dict 1 = {}

Dict1[mykey] = helloworld # directly assigns a value to a nonexistent key-value pair, and instantly adds new elements.

Dict 1 [(my,key)]

# Number of key-value pairs

Print lens (dict 1)

# Check the key

Print mykey in dict 1 #True to check whether there is a key-value pair with mykey.

Print hello in dict 1 #False.

# Delete

Del dict 1[mykey] # Delete the key-value pair with mykey.

Continue to use the above methods to view all public methods of the dictionary:

[x for x in dir({ })if not x . starts with(_ _)]

[clear,copy,fromkeys,get,has_key,items,iteritems,iterkeys,itervalues,

keys,pop,popitem,setdefault,update,values,viewitems,viewkeys,viewvalues]

Dict.clear () deletes all elements in the dictionary.

Dict.copy () returns a copy of the dictionary (shallow copy).

Get (key, default=None) returns the value corresponding to the key in the dictionary Dict, and if the key does not exist in the dictionary, returns the value of default (note that the default value of the parameter default is None).

Dict.has_key(key) returns True if there is a keyword in the dictionary, otherwise it returns False. After Python2.2 was introduced in rather than in, this method has almost been abandoned, but it still provides a working interface.

Dict.items () returns a list of (key, value) pairs in the dictionary.

Dict.keys () returns a list containing the keys in the dictionary.

Dict.values () returns a list containing all the values in the dictionary.

Dict.iter () method iter item (), ITER key () and ITER value () are the same as their corresponding non-iterative methods, except that they return iterators instead of lists.

Dict.pop(key[, default]) is similar to the get () method. If the keyword key exists in the dictionary, it will be deleted and returned. If key key does not exist and no default value is given, a KeyError exception will be thrown.

Dickert. Setdefault (key, default = none) is similar to method set (). If there is no key in the dictionary, it will be assigned by dict[key]=default.

Dickert. Setdefault (key, default = none) is similar to method set (). If there is no key in the dictionary, it will be assigned by dict[key]=default.

boolean type

Boolean types are true and false, just like other languages. Typical Boolean values are listed below.

Print bool(0) #False

print bool( 1) #True

Print Boolean value (-1) #True.

Print Boolean value ([]) #False

print bool(()) #False

Print Boolean value ({}) #False

Print bool() #False

Print Boolean value (None) #False