Python Learning Note II (data type)

Source: Internet
Author: User

First, the number

Mainly includes shaping and floating-point type, which are immutable types.

Integer: defined as num = 1

Floating point type: Definition method height = 179.9

Second, string

In single, double, or triple quotation marks, consists of a string of characters that are immutable types.

Defined in the way name = "XXX"

The main operations are as follows:

1. Value by index.

s = "Hello World" print (s[1])  #打印字母 ' e ' Print (s[-1])  #打印字母 ' d '

2. Slicing

#切片原则为顾头不顾尾s = "Hello World" print (S[0:4])    #获取前四个子串, the index head does not count from 0 to 3print (S[::2])   #每次间隔一个字符获取字符串子串print (s[3:1:- 1]) #从索引3开始到索引1以后, inverted output print (s[-1::-1])  #所有元素反转输出

3. Length

s = "Hello World" Print (s.__len__()) print (Len (s))        #实际仍然是调用的s. __len__ ()

4. Member operations in and not in

s = "Hello World" Print (' W ' in s)    #Trueprint (' l ' not in s)   #False

5. Remove the blank strip

s = "   Hello World   " Print (S.strip ())    #移除字符串左右的空白print (S.lstrip ())   #移除字符串左侧的空白print (S.rstrip ())   #移除字符串右侧的空白s = "****abc*******" Print (S.strip (' * ')) #移除字符串左右的 *

6. Splitting split

passwd = "Test:x:504:501::/home/test:/bin/bash"
Print (Passwd.split (': ')) #将字符串以冒号作为分隔符, divided into several strings placed in the list
Print (Passwd.split (': ', 1)) #只分割遇到的第一个分隔符拆分
Print (Passwd.rsplit (': ', 1)) #从右侧开始, first delimiter split

7. Cycle

s = "Hello World" #依次打出每个字符for i in s:    print(i) #间隔1个打出字符for I in range (0,len (s), 2):    print (s[i]) 
       

8.lower,upper,startswith,endswith

s = "Hello World" Print (S.upper ())  #所有字母大写print ("Hello". Lower ())  #所有字母小写print (s.startswith (' Hello ')) Print (S.endswith (' World)) print (S.endswith (' d '  ))

9.format

Print (' My name is ' {},my ' {} '. Format (' xxx ', ') 'print (' My name is ' {1},my ' {0} ') '. Format (' xxx ') 'print (' m Y name is {name},my-age} '. Format (age=99,name= "xxx")) 

10.join

L = [' A ', ' B ', ' C ', ' d ', ' e ']  #使用join时, all elements in the list must be string print (' * '. Join (L)) print (". Join (L ))

11.replace

s = ' Hello World ' print (s.replace (' O ', ' @ ')) print (S.replace (' O ', ' @ ', 1))  #只替换第一个

12.isdigit

A = "sljfljjlkjsdfl33" For I in A:    print (I.isdigit ())   #只有循环到最后两个字符时打印True

Third, List

1. Value by index.

L = [' A ', ' B ', ' C ', ' d ']print (l[2])   #打印第三个元素cprint (l[-2])   #打印倒数第二个元素c

2. Slicing

#切片原则是骨头不顾尾l = [' A ', ' B ', ' C ', ' d ', 1,2,3,4]print (L[0:4])    #获取前四个元素, the index head does not count from 0 to 3print (L[::2])   # One fetch list element per interval print (L[3:1:-1]) #从索引3开始到索引1以后, inverted output print (l[-1::-1])  #所有元素反转输出

3. Length Len

L = [' A ', ' B ', ' C ', ' d ', 1,2,3,4]print (l.__len__()) print (Len (l))        #实际仍然是调用的l. __len__ () 

4. Member operations in and not in

L = [' A ', ' B ', ' C ', ' d ', 1,2,3,4]print (' C ' in L)    #Trueprint (1 No in L)   #False

5. Append

L = [' A ', ' B ', ' C ', ' d ', 1,2,3,4]l.append (' e ') print (l) 

6. Delete

#del和remove为单纯的删除, pop for get deleted element L = [' A ', ' B ', ' C ', ' d ', 1,2,3,4]del l[7]   #删除最后一个元素print(L) l.remove (' a ')  #删除元素 ' A ' Print (L.pop ())  #删除并获取最后一个元素print (L.pop (2))  #删除并获取第三个元素

7. Cycle

L = [' A ', ' B ', ' C ', ' d ', 1,2,3,4]for i in L:    print(i)-I in range (len (l)):    print (l[i]) 

8. Invert and sort

#排序是元素必须是字符串类型l = [' A ', ' e ', ' X ', ' 8 ', ' Q ', ' n ', ' ww ', ' EE ', ' 3 ']l.reverse ()  #反转列表print (L) l.sort ()     # Forward sort print(l) l.sort (reverse=true)   #反向排序print (l)  

9. Other methods

L = [' A ', ' B ', ' C ', ' d ', 1,2,3,4]l.insert (2, ' xx ')  #在第三个索引位置插入一个字符串print(l) L1 = l.copy ()   #拷贝l中所有元素print (L1) print (ID (l), id (L1))  #列表ID不同l. Clear ()       #清空列表内的所有元素print(l) Print (L1.count (' C '))   # The number of occurrences of an element in the statistics list L2 = [' AA ', ' BB ', ' cc ', and ' C ']l1.extend (L2)   #扩展l1, the two lists are stitched together and the print(L1) print ( L1.index (' C ')) print (L1.index (' yy '       )) #传入不存在的元素时会报错

Four, the tuple

Multiple values can be stored in a tuple, but cannot be added and deleted to tuples.

1. Take the value

#按照索引取值t = (' A ', ' e ', ' X ', ' 8 ', ' Q ', ' n ', ' ww ', ' EE ', ' 3 ') print (t[4])

2. Slicing

#顾首不顾尾, same list and string t = (' A ', ' e ', ' X ', ' 8 ', ' Q ', ' n ', ' ww ', ' EE ', ' 3 ') print (T[2:5]) print (t[-1::-1]) 

3. Length

#顾首不顾尾, same list and string t = (' A ', ' e ', ' X ', ' 8 ', ' Q ', ' n ', ' ww ', ' EE ', ' 3 ') print (len (t))

4. Length and Member operations

t = (' A ', ' e ', ' X ', ' 8 ', ' Q ', ' n ', ' ww ', ' ee ', ' 3 ') print (len (t)) print (' ww ' in T) print ( ' EE '  is not in T) 

5. Cycle

t = (' A ', ' e ', ' X ', ' 8 ', ' Q ', ' n ', ' ww ', ' EE ', ' 3 ') for I in t:    print(i) for I in range (len (t)):    print (t [i])   

5.index and Count

t = (' A ', ' e ', ' X ', ' 8 ', ' Q ', ' n ', ' e ', ' ww ', ' EE ', ' 3 ') print (T.index (' Q '))print (T.index (' aaa '))   # Error print (T.count (' e ')) if not present 

Five, dictionary

Multiple values can be stored in a dictionary, accessed using Key-value, and is faster. Where key must be an immutable type, such as a number, a string, a tuple, and so on, the value can be any type.

1. Access

info={' name ': ' xxx ', ' age ': A, ' sex ': ' Male '}print (info[' age ') ' info[' hobby '] = ' basketball ' Print (info) 

2. Length and Member operations

info={' name ': ' xxx ', ' age ':, ' sex ': ' Male '}print (len (info))  #返回key的个数print (' name ' in info) print (' xxx ') In info)  #返回False, indicating that in can only determine if key is in the dictionary, cannot judge Valueprint (' male ' not in info) #返回True 

3. Delete

info={' name ': ' xxx ', ' age ': A, ' sex ': ' Male '}del info[' name ']print(info) print (Info.pop (' age '))  # Delete the key-value pair and return the value of the key corresponding to print (Info.popitem ())   #随机删除一个键值对, and return the key value pair   with the tuple

4.keys,values,items

info={' name ': ' xxx ', ' age ': A, ' sex ': ' Male ', ' hobby ': ' Basketball '}print (Info.keys ())  #返回字典的key对象, can be used to loop through print (List (Info.keys ()))  #转换为包含所有key的列表print (Info.values ())    #同上, return all values print (Info.items ())     #同上, returns all key-value pairs

5. Cycle

info={' name ': ' xxx ', ' age ': A, ' sex ': ' Male ', ' hobby ': ' Basketball '}for key in info:    print (Info[key]) 

6.setdefault

#若key存在, no value is assigned, if key does not exist then set default value info={' name ': ' xxx ', ' age ': ' Male ', ' hobby ': ' Basketball '}info.setdefault ('  #不会修改age的值print(info) info.setdefault (' Country ', ' China ') #country不存在, add the key-value pair print (info) 

Six, the collection

A collection can contain multiple elements, separated by commas, and all elements must be immutable types, elements unordered and non-repeatable. The main function is to perform relational operations.

1. Collection creation

A = {3, "AAA", ' xxx ', 222, "as", ' EE ', 3}print (a)   #自动去重并改变顺序

2. Length and Member operations

A = {3, "AAA", ' xxx ', 222, "as", ' EE ', 3}print(Len (a)) print (222 in a) print (' EE ' not in a)  

3. Collection |

A = {3, "AAA", ' xxx ', 222, "as", ' EE ', 3}b = {' ff ', ' BBB ', 3, ' ee ',}print (a|b) 

4. Intersection &

A = {3, "AAA", ' xxx ', 222, "as", ' EE ', 3}b = {' ff ', ' BBB ', 3, ' ee ',}print (a&b) 

5. Difference Set-

A = {3, "AAA", ' xxx ', 222, "as", ' EE ', 3}b = {' ff ', ' BBB ', 3, ' EE ',}print (A-B)  #在a中不在b中

6. Symmetrical difference Set ^

A = {3, "AAA", ' xxx ', 222, "as", ' EE ', 3}b = {' ff ', ' BBB ', 3, ' ee ',}print (a^b)  #只在a中或只在b中的所有元素

7.==

A = {3, "AAA", ' xxx ', 222, "as", ' EE ', 3}b = {' ff ', ' BBB ', 3, ' ee ',}print (a==b)  #a和b元素不同, return false 

8. Parent set and subset

A = {3, "AAA", ' xxx ', 222, "as", ' EE ', 3}b = {3, ' ee '}print (a>b)  #a是b的父集, return trueprint (a>=b) Print ( B<a)  #b是a的子集, return to Trueprint (b<=a)  

Seven, character encoding

How the 1.python interpreter executes the py file

First stage: The Python interpreter starts, which is equivalent to launching a text editor.

Second stage: The Python interpreter is equivalent to a text editor to open the Py file, read the Py file on the hard disk into memory (the explanatory nature of Python determines that the interpreter cares only about the content does not care about the suffix)

Phase three: The Python interpreter interprets the execution of the py code loaded into memory (this phase recognizes the Python syntax, executes the code in the file, and, when executed into an assignment statement, opens up memory space for the variable)

2. Common coding

ASCII is the earliest character encoding, with a maximum of 8 bits to represent English letters, numbers, and special characters, that is, 2**8=256 symbols.

Unicode commonly uses 2 bytes to represent one character, and 4 bytes for uncommon characters. Unified in memory Unicode, waste space in exchange for can be converted to arbitrary encoding (not garbled), the hard disk can use a variety of codes, such as Utf-8, to ensure that the data stored on the hard disk or network-based transmission is very small, improve transmission efficiency and stability.

UTF-8 encodes a Unicode character into 1-6 bytes based on a different number size, the commonly used English letter is encoded in 1 bytes, the kanji is usually 3 bytes, and only the uncommon characters are encoded into 4-6 bytes. UTF-8 can save space.

3. The law of not garbled

To ensure that the core law is not garbled, the character according to what the standard encoding, it is necessary to follow what standard decoding. All characters written in memory are Unicode encoded.

In the second phase, use #coding: Utf-8 to determine what encoding format to read the source into memory.

In the third stage, use #coding: Utf-8 to determine how the string is encoded in memory. With the print output, the terminal encoding must be consistent with the #coding, window terminal default is GBK, if the use of Unicode format data, no matter how printing is not garbled.

4. Coding Summary

The type of STR in Python2 is the type of bytes in Python3.

Viii. Processing of documents

File read operations

#打开文件, get the file handle and assign a value to the variable f = open (' A.txt ', ' R ', encoding= ' utf-8 ')   when the file is saved using Utf-8, you need to decode with utf-8. data = F.read () f.close () 

If you do not want to use F.close (), use the WITH keyword

With open (' A.txt ', ' R ') as F:    Pass withopen (' A.txt ', ' R ') as Read_f,open (' B.txt ', ' W ') asWrite_f:    data = Read_f.read ()    write_f.write (data)   

Python Learning Note II (data type)

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.