Python Road DAY02-Basic data types and coding

Source: Internet
Author: User
Tags shallow copy

 

Basic article

This chapter outlines:

character encoding and interpreter codingVariable naming rules  base data type (i) intunderlying data type (b) stringunderlying data type (iii) BOOLbasic data type (iv) List
Underlying data type (v) tuplebasic data Type (vi) dict
Basic data Type (vii) Set supplemental iterative object loop connection and enumerate output character encoding and interpreter coding
One, the importance of encoding: 1.1 File encoding and character editing encoding and reading code
#!/usr/bin/env python#-*-coding:utf-8-*-with open (' acsii_01 ', ' A + ', encoding= ' utf-8 ') as F:    f.write (' li Jie ' + ' \ n ') With open (' acsii_01 ', ' R ', encoding= ' utf-8 ') as f:    data = F.read ()    print (data)

Summarize:

Note: The encoding problem of the file operation is treated. The encoding of the annotated file can be in any encoding format. However, the encoding to be written must be the same as the read encoding. In fact, this involves the file storage coding problem. Below we can read the file in binary format to see how different encoding formats are stored in the files:

In addition, if you are reading a file, use the RB mode. You do not need to specify encoding. Encoding's job is that when your file operation's encoding is not UTF-8 (the default encoding for the Python3 character operation is Utf-8), you will need to specify the encoding for the specified read file.
#!/usr/bin/env python#-*-coding:utf-8-*-with open (' acsii_01 ', ' RB ') as F:    data=f.read ()    print (' acsii ', data) With open (' acsii_02 ', ' RB ') as F:    data=f.read ()    print (' Utf-8 ', "data") with open (' acsii_03 ', ' RB ') as F:    data= F.read ()    print (' GBK ', data) with open (' acsii_04 ', ' RB ') as f:    data = F.read ()    print (' Unicode ', data)

  

Summarize:

character encoding note read-write encoding to be always. In addition, file encoding and read-write encoding of the document operation is actually related. As long as you write the encoding and read the encoding consistent, you can read the file normally. It is recommended to specify the encoding for file read and write when file operation. Of course, if the mode of reading is RB, there is no need to specify the encoding format. The next character encoding and the Python interpreter encoding are different. The Python interpreter's encoding is used to compile the Python process to read the production byte code.   Character encoding is an operation on a character.  Variable naming rule One, variable naming rules: 1, cannot start with a letter 2, cannot be the same as built-in variables. 3, cannot start with a special meaning character

Basic data type (i) int one, shaping
A=1

  

Basic data type (b) string two, a common method of string is as follows:
#字符串首字母大小. Other letters lowercase s= ' Alxe\ttiantao3 ' Data=s.capitalize () print (data) #转换成小写. The Data=s.casefold () print (data) #转换成小写 for all Unicode characters. Only A-Z conversion within ASCII can contain special characters%, @data =s.lower () print (data) str1= ' alex$%@ ' Data=str1.lower () print (data) #居中填充 #20 as length. * For filled characters, you can Nonedata=s.center ("*") print (data) #统计字符. You can specify that the index and end Indexdata=s.count (' a ', 0,-1) print (data) #指定编码errors =no ignore the error Data=s.encode (encoding= ' utf-8 ', errors= ' No ') print (') print (') #以指定的字符结尾data =s.endswith (' ao ') print (data) #以指定的字符开始data =s.startswith (' Al ') print (data) #去掉制表符 \ t. #0是指从起始位置到制表符长度. The length is insufficient for blank padding. #另外注意长度最好指定. The default has a length of print (s) data=s.expandtabs (0) print (Data,len (data), Len (s), Len (' alEx ')) #查找字符串 # Returns the starting index of the first string found, you can specify Start,enddata=s.find (' a ') print (data) #字符串格式化输出data = ' output%s '% (s) print (data) Data= ' output {a} '. Format (a=s) print (data) data = ' Output {a} '. Format_map ({' A ': s}) print (data) #查找字符串的index. #显示字符串起始index. You can specify Start,enddata=s.index (' al ') print (data) #isalnum检测字符串是否有字母和数字组成str1 = ' alextian2 ' Data=str1.isalnum () print (data ) #isalpha是否为英文字母str1 = ' AlextiaN ' Data=str1.isalpha () print (data) #是否是数字isdecimalstr1 = ' 22222 ' Data=str1.isdecimal () #只能判断纯数字print (data) str1= ' 2222① ' Data=str1.isdigit () #可以判断特殊的数字print (data) str1= ' 2222① two ' data=str1.isnumeric () #可以判断特殊的数字print (data) # Isidentifier test is not a valid variable str1= ' 2ceshi ' Data=str1.isidentifier () print (data) str1= ' Ceshi ' Data=str1.isidentifier () Print (data) #是否是小写字符str1 = ' zaddd ' Data=str1.islower () print (data) str1= ' aaddd% ' Data=str1.islower () print (data) # Isprintable If there is a newline tab \ r \ n \ \tstr1= ' Alex Tian ' data=str1.isprintable () print (data) str1= ' alex\n Tian ' data= Str1.isprintable () print (data) str1= ' alex\t Tian ' data=str1.isprintable () print (data) str1= ' Alex Tian ' data= Str1.isprintable () print (data) #isspace是否全部是空格str1 = ' Data=str1.isspace () print (data) #istitle是否是标题 # each word capitalized str1= ' Alex Shangshan ' Data=str1.istitle () print (data) #循环连接所有可迭代str1 = ' Alex ' data= ' _ '. Join (STR1) print (data) #左填充右填充str1 = ' Alex ' Data=str1.rjust (' * ') print (data) #移除空格或者换行str1 = ' Alex ' Data=str1.strip () #对应和翻译m = Str.maketrans (' al ', ' @@ ') str1= ' Alex Tian ' data=str1.translate(m) print (data) #以字符界限分割str1 = ' Alex ' data=str1.partition (' l ') print (data) data=str1.split (' L ') print (data) # Remove the inner line break str1= ' Alex\ntian ' Data=str1.splitlines () print (data) #指定查找替换和替换个数str1 = ' Alex ' Data=str1.replace (' A ', ' A1 ', 1) Print (data) #字符串转小写. Uppercase to lowercase. lowercase to uppercase str1= ' Alex ' Data=str1.swapcase () print (data) #小写转大写str1 = ' Alex ' Data=str1.upper () print (data) #标题str1 = ' Alex Tiantao ' Data=str1.title () print (data) #从左边用0填充字符串str1 = ' Alex ' Data=str1.zfill print (data)

Chapter on string slices



Underlying data type (iii) BOOL III, value and judgment rule of type bool
Print (bool (1)) print (bool (0)) print (bool (-1))

Summarize:

‘‘‘
summarize BOOL Types
0 is false, not 0 is true
void false non-NULL is true (both characters and objects can be judged)

‘‘‘

Basic data Type (iv) list four, summary of list methods
#################################### #list ############################### #注意列表是可变元素故此有一些方法或者属性可以直接在列表上操作. Or there is a return value # Add list element list1=[]v=list1.append (' Alex ') print (v) print (list1) #清空列表元素v =list1.clear () print (v) print (list1) # Shallow copy element # Shallow copies, copies only the parent object, does not copy the child objects in the parent object; Deepcopy is a deep copy, which can be thought of as a complete copy of the past; List1=[1,2,3,[1,2,3,4]]list2=list1.copy () list1[-1] [0]=2print (List1,list2) list1[0]=2print (list1,list2) #count计数list1 =[1,2,3,4,5,5]data=list1.count (5) print (data) # Extend Extended List1=[1,2,3,4,5,5]data=list1.extend ([1,2,3,4]) print (data) print (List1) #index索引list1 =[1,2,3,4,5,5]data= List1.index (5) print (data) #insert指定index位置插入list1 =[1,2,3,4,5,5]data=list1.insert (2,[4,3,4]) print (LIST1) # Pop pops an element. You can specify Indexlist1=[1,2,3,4,5,5]data=list1.pop (2) print (List1) #remove移除指定元素list1 =[1,2,3,4, ' 5 ', ' 5 ']data= List1.remove (' 5 ') print (list1) #reverse翻转listlist1 =[1,2,3,4, ' 5 ', ' 5 ']data=list1.reverse () print (List1) #sort排序list1 =[1,2,3,4,5,5]data=list1.sort () print (List1) list1=[1,2,3,4,5,5]data=list1.sort (reverse=true) print (List1)

  


Underlying data type (v) tuple


Five, the meta-ancestor class instantiation method is as follows:
#index通过value找indextuple1 = (1,2,3,4) data=tuple1.index (3) print (data) #count统计valuetuple1 = (1,2,3,4) data= Tuple1.count (2) print (data)

  

Basic data Type (vi) dict
Six, the Dictionary instantiation object method is as follows:
#clear清空dict1 ={' v1 ': ' Alex ', ' v2 ': ' Tian '}dict1.clear () print (dict1) #copy浅copydict1 ={' v1 ': ' Alex ', ' v2 ': ' Tian '}dict2 =dict1.copy () print (DICT2) #fromkeys dictionary static method loop list Create dictionary # Note that key must be immutable element. In addition value modification, other elements will also be modified Dict1=dict.fromkeys ([' V1 ', ' v2 '],123) print (dict1) #get方法获取指定key的valuedict1 ={' v1 ': ' Alex ', ' v2 ' : ' Tian '}data=dict1.get (' v1 ') print (data) #items返回一个可循环的元祖的listdict1 ={' v1 ': ' Alex ', ' v2 ': ' Tian '}data=dict1.items () Print (data) for Key,value in Dict1.items (): Print (key,value) #keys或者字典的所有的keydict1 ={' v1 ': ' Alex ', ' v2 ': ' Tian '}data= Dict1.keys () print (data) #pop弹出一个指定键值对, returns the corresponding valuedict1={' v1 ': ' Alex ', ' v2 ': ' Tian '}data=dict1.pop (' v1 ') print (data) Print (DICT1) #popitmes随机弹出一个指定键值对, returns the corresponding valuedict1={' v1 ': ' Alex ', ' v2 ': ' Tian '}data=dict1.popitem () print (Data,dict1 ) #setdefaul setting to add an element. Presence does not add dict1={' v1 ': ' Alex ', ' v2 ': ' Tian '}data=dict1.setdefault (' v3 ', ' Li ') print (data,dict1) #update更新字典dict1 ={' v1 ': ' Alex ', ' v2 ': ' Tian '}data=dict1.update ({' V1 ': ' Zhangsan ', ' V3 ': ' Lisi '}) print (Data,dict1) #values获取字典的valuesdict1 ={' V1 ': ' Alex ', ' v2 ': ' Tian '}data=dict1.values () print (DATA,DICT1) "Note that the key to the dictionary must be a variable hash of immutable objects" 

  

Underlying data type (vii) set
Seven, the Set collection object instantiation method is as follows:
#add Add an element Set1={1,2,4,5}data=set1.add (' 6 ') print (Set1) #clear清除元素set1 ={1,2,4,5}data=set1.clear () print (SET1) # Copy Shallow copyset1={1,2,4,5}set2=set1.copy () print (Set2) #集合比较 the difference between #difference Set1 and Set2. Set1 some Set2 have no set1={1,2,4,5}set2={1,2,3,5}data=set1.difference (set2) print (data) #difference_update把差集赋值给set1set1 = {1,2,4,5}set2={1,2,3,5}data=set1.difference_update (Set2) print (DATA,SET1) #discard移除元素set1 ={1,2,4,5}data= Set1.discard (5) print (Set1) #交集intersectionset1 ={1,2,4,5}set2={1,2,3,5}data=set1.intersection (set2) print (data) # Intersection_update #union set1={1,2,4,5}set2={1,2,3,5}data=set1.union (set2) print (data) # Isdisjoint if no intersection is Trueset1={1,2,3,5}set2={6,7}data=set1.isdisjoint (set2) print (data) #issubset判断是不是子集set1 ={1,2} Set2={1,2,3,5}data=set1.issubset (Set2) print (data) #issuperset判断是不是父集set1 ={1,2}set2={1,2,3,5}data= Set2.issuperset (SET1) print (data) #pop弹出一个集合元素set1 ={1,2}data=set1.pop () print (data) #remove移除一个元素set1 ={1,2}data= Set1.remove (2) print (Set1) #symmetric_difference对称差集. Set of difference sets Set1={1,2,6,7}set2={1,2,3,5}data=Set1.symmetric_difference (Set2) print (data) #update更新集合set1 ={1,2,6,7}data=set1.update ({4,5,6}) print (DATA,SET1) 

  

Complement the cyclic connection and enumerate output of an iterative object and summarize one, the connection of the object can be iterated into a string '. Join ()
#可迭代对象的链接及输出str1 = ' Alex ' str1= ' + '. Join (a) print (str1) list1=[' 1 ', ' 2 ']list1= ' + '. Join (list1) print (list1) tuple1= (' 1 ', ' 2 ') tuple1= ' + '. Join (list1) print (tuple1) dict1={' v1 ': ' Alex ', ' v2 ': ' Tian '}dict1= ' + '. Join (list1) print (DICT1) set1={ 1,2,3}set1= ' + '. Join (SET1) print (SET1)

  

Summary: 1, an iterative object can be used to iterate over the connection string two using the Join method, and the loop output iterates over the object
#enumerate方法返回一个 [(Index,enumer)]data=enumerate (list1) print (data) for line data:    print (line) data=enumerate ( List1) for Index,enum in data:    print (Index,enum)

  

Summary: 1, notice that the iterator is assigned to an object. If the iterator __next__ has been looped over. The next object will not have any more elements to iterate over, so the iteration end 2,enumerate method returns a list of elements that are tuple [(Index,enumer)]

Python Road DAY02-Basic data types and coding

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.