Python Basic data type

Source: Internet
Author: User

Python's basic data includes the following:

    • Number
    • Character String
    • Lists List
    • Tuple tuples
    • Dictionary Dictionary

Digital

Python3 supports int, float, bool, complex (plural).

In Python 3, there is only one integer type int, represented as a long integer, and no long in Python2.

Boolean value:

x =0     # in integers except 0 is false, negative numbers and positivenumbers are true y =[]    # empty list is false, inverse is truez='      # null string is False, inverse is trueprint(bool (x), bool (y), bool (z))
False false

Character String

List(List/arrays/array), which is called subscript/index/corner superscript when the subscript of the first element is 0, the subscript of an element in the last face is-1
Cities=[]#to define an empty list#add ElementCities.append ('Beijing')#add an element to the end of the listCities.insert (0,'Shanghai')#inserts an element at the specified position, only one at a time. The insert subscript cannot be a negative number. 
#Delete ElementCities.pop (-1)#deletes the specified element, passing the subscriptCities.remove ('Beijing')#deletes the specified element, passing the elementCities.clear ()#Clear ListdelCITIES[-1]#deletes the element at the specified position, passing the subscript
#
ModifyCITIES[1] ='Nanjing' #Specify a subscript, modify it directly, and specify that the subscript cannot exceed the existing subscript range.
#
EnquiryPrint(cities)#Print the entire listPrint(Cities[0])#prints the element at the specified positionPrint(Cities.index ('Guangzhou')#gets the index of the element, if the element does not exist, the errorPrint(Cities.count ('Guangzhou')#The view element appears several times in the listPrint(Cities.reverse ()) #输出None, but reversed the list to re-print (cities) to see the result ==>cities.reverse ()Print(cities) cities.sort ()#Default Ascending sortCities.sort (reverse=True) #降序排序, sorted by number or letter Print(Cities1 + cities2)#Merge Listmultidimensional array Two-dimensional array: The list contains a nested array,#slices, which are a way to take a list of valuesPrint(Nums[1:3])#slicing the head regardless of the tailPrint(nums[1:])#If you start from one subscript to the end, the subscript at the end can be omittedPrint(Nums[:2])#if it is taken from scratch, take it to the end of one of the following subscripts, the subscript at the beginning may not be writtenPrint(nums[:])#Remove All
#
Loops forIinchRange (1,4):#range () also Gu Tou disregard the tail Print(i)#Printing results: 1, 2, 3Lis= List (range (1,21))#type conversion to listPrintlis (LIS)= List (range (1,21))Print(Lis[1:10:2])#step, take a number 2, to the 9th subscriptLis= List (range (1,21))Print(Lis[::-1])#If the step is positive, the value is taken from left to right, and if the step is negative, the value is taken from right to left. The equivalent of reversing the list. The difference from. Reverse () is that:. Reverse () changes the contents of the list. #When the step is negative, the a:b:-1,a must be greater than B, otherwise the value is emptyFor example: Lis= List (range (0,21))Print(LIS)Print(Lis[21:10:-1])#from subscript 21 to subscript 10, but does not include 10 subscript: [ ,, +, +, +, +,----]Print(Lis[:18:-1])#from subscript maximum to subscript 18, but does not contain 18 subscript: [+]Print(Lis[0::-1])#from subscript 0 to the smallest subscript, take only 0 subscript: [0]Print(Lis[::-1])#from subscript maximum to smallest: [9, 7 , 5, 4, 3, 2, +, +, +, +, 8, +, +, +, +]s='Abcdefghi's[3] ='h' #string variable can not be modified, error: TypeError: ' str ' object does not support item assignmentlists= ['AAA','BBB','CCC','DDD'] forNameinchLists#iterate through every element in the array Print(name) words='Marry,lily,joker' forNameinchWords#iterate through every character in a string Print(name)#The For loop iterates through every element of the loop as it iterates through the objects. #if it is a multidimensional array, determine the type. Lists = ['AAA','BBB','CCC','DDD', [1,2,3,4]] forNameinchlists:if type (name) = = List:    For i in name: Print(i) #打印列表中的列表: 1 2 3 4
Meta-group: The tuple is also a list, and the difference between it and the list is that the elements inside the tuple cannot be modified
T = ('AAA','BBB','CCC','DDD','ee')Print(Type (t))#<class ' tuple ' >Print(T[:3])#tuple slices: (' aaa ', ' BBB ', ' CCC ')Print(t[4:])#(' ee ',)Print(T.index ('AAA'))#find the subscript of an elementPrint(T.count ('AAA'))#There are only two ways to find the number of elements, and tuples cannot be modified. T2= (1,2,4) Words= (1) Words2= ('ABC')Print('T2', type (t2))#T2 <class ' tuple ' >Print('words', type (words))#words <class ' int ' >Print('Words2', type (WORDS2))#words2 <class ' str ' >#If there is only one element in the tuple, then you must add a comma after the element to be a tuple. 

Dictionary: Is the form of the Key-vaule 1. Easy to access data 2. Fast speed
IFOs ={'name':'AAA','Sex':'male',' Age': 18}#check: Dictionary values are in either of these ways:Print(Ifos.get ('name'))#If key does not exist, none is returnedPrint(ifos['name'])#If key does not exist, the error isPrint(Ifos.get ('AAA','Phone'))#Specifies that if you do not get the AAA key, the default phone, which is another method of get#Increaseifos['Phone']=1852003000#The dictionary is unordered, the added value is not necessarily at the end, if key exists, it is modifiedIfos.setdefault ('Height','BBB')#another way to add a dictionary#Changeifos['name']='YYYY' #if the key already exists, the value of name can be modified in this way, only oneIfos.setdefault ('name','EBB')#If key already exists, the value of name cannot be modified in this way#DeleteIfos.pop (' Age')#Specify key to deleteIfos.popitem ()#randomly delete a keydelifos['Phone']#Specify key to deleteIfos.clear ()#Empty Dictionarydictionary Built-in methods:Print(Ifos.values ())#get to the dictionary all the Value:dict_values ([' AAA ', ' Male ',]:Print(Ifos.keys ())#get all the Key:dict_keys to the dictionary ([' name ', ' sex ', ' age ')Print(Ifos.items ())#get all the K-v:dict_items to the dictionary ([' Name ', ' AAA '), (' Sex ', ' Male '), (' Age ', ')])#Loops forPinchpeople:Print(p)#When you cycle a dictionary, the key of the dictionary is printedCommon string methods: a='\ n string \ n'C= A.strip ()#by default, spaces and line breaks are removed before and after the stringC= A.lstrip ()#by default, whitespace and line breaks in front of the string are removedC= A.rstrip ()#by default, spaces and line breaks after a string are removed

Python Basic data type

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.