Python the next day

Source: Internet
Author: User

Day-2 notes:
1, is comparison is id,== comparison is value (value)

2. Variable value interchange method, intermediate variable
Method Two: X,y=y,x
3, in the level of comparison or, if the left of or is true, then the entire result is true.
4, the number types are: int, float, plural:
Emphasis on plural:
X=1-2j
Print (x.real) #查看复数的实部
Print (X.IMAG) #查看复数的虚部

5, about the conversion of the binary:
Bin () Binary: Represents the beginning of the 0b
Oct () Octal: starting at 0o
Hex () 16 binary: Start on behalf of 0x

6. There are multiple characters in Python, but there is only one value.
7, about the input in Python when the space, not conducive to our later value comparison: so we use the following methods to set:
A=input (' >>: ')
A.replace (",") #可以用replace (",") to remove all the spaces in the string, or to replace the string, and the third parameter to indicate the number of substitutions:
>>> name = input (' ussername: '). Replace (' AA ', ')
>>> AA cc
Name
' CC '
#
A.strip () #把输入的字符串的头部和尾部的空格去掉.
A.lstrip (): #把左边的空格去掉
A.rstrip (): #把右边的空格去掉
Len () #打印字符串的长度

8. Cutting of the Python string: Split
Split usage: The first thing to do is to follow the cut and then add the number of cuts.
eg.:
user_info= ' Root:0:0:0::/root:/bin/bash '
Print (User_info.split (': ') [5])
/root
EG1:
user_info= ' Root:0:0:0::/root:/bin/bash '
Print (User_info.split (': ', 1) [0])

9. Look at the length of the string using the Len () method.
Split () cuts the string operation.
Slice of string: Gu Tou regardless of tail.
Name= ' Hello word '
Print (Name[1:3]) #取从1到3
Print (Name[1:3:1]) #从1到3中间隔一个字符

10, judge the character of the string:
EndsWith () #以什么字符串为结尾, returns the result as a Boolean value
StartsWith () #以什么字符串为开头, the return value is Boolean
Replace () #替换字符串

11, Fromat

Print (' {} {} {} '. Format (' XM ', ' One ', ' Male '))
Print (' {0} {0} {1} '. Format (' XM ', ' One ', ' Male '))
Print (' Name:{name} age:{age} sex:{sex} '. Format (name= ' XM ', age= ' one ', sex= ' Male '))


12, judge whether the number:
Num= ' 123 '
Print (Num.isdigit ()) #判读是否为数字, only the Beyt type and the Unicode type can be judged.
Num.isnumberic #判断数字类型有中文数字, Roman numerals, u types.

13, find () #查找字符串, if there is a return true.
Count () #统计次数
Lower () #大小字母转小写
Upper () #将小写字母转大写
Index () #取出字符在字符串中的索引位置

14. It is used to store several different values.

Second, the list of processing methods:
1, append () #添加值到列表从左到右
2. Pop () #按照索引数字删除
3. Remove () #按照列表的值删除
4, Len () #统计列表元素的个数
5, in #包含
6, Cleari () #清楚列表
7. Copy () #拷贝列表
8, COUNT () #统计元素的count
9, Extend () #添加多个元素到列表
10. Index () #查看元素的下标
11, reverse () #反转
12. Sort () #对列表的元素进行排序
13. Insert () #指定位置插入

14. Queue: FIFO,
Stacks: Advanced back-out,

15. String placeholder:
msg= ' Hello '
A,b,c,_,e=msg
Print (A, B)
H E
#
msg= ' Hello '
A,*_,b=msg
Print (A, B)

16. Analog Queue:
#队列, FIFO
Fifo=[]
Fifo.append (' fist ')
Fifo.append (' second ')
Fifo.append (' third ')
Print (FIFO)
Print (Fifo.pop (0))
Print (Fifo.pop (0))
Print (Fifo.pop (0))
Print (")

#insert方法模拟队列:
Fifo.insert (0, ' fist ')
Fifo.insert (0, ' second ')
Fifo.insert (0, ' third ')
Print (FIFO)
Print (Fifo.pop ())
Print (Fifo.pop ())
Print (Fifo.pop ())

#模拟堆栈
Lifo=[]
Fifo.append (' fist ')
Fifo.append (' second ')
Fifo.append (' third ')
Print (FIFO)
Print (Fifo.pop ())
Print (Fifo.pop ())
Print (Fifo.pop ())
#insert方法模拟堆栈
Fifo.insert (0, ' fist ')
Fifo.insert (0, ' second ')
Fifo.insert (0, ' third ')
Print (FIFO)
Print (Fifo.pop (0))
Print (Fifo.pop (0))
Print (Fifo.pop (0))


17, tuples immutable, mainly for reading operations, is an immutable list.
The elements of the tuple are ordered and the list is ordered.


18. The dictionary is a mutable type. But the key in each element of the dictionary is immutable, the value is mutable, the memory is more than the list, and the elements of the dictionary are unordered.


#默认值, returns the default when the value does not exist.
info={' name ': ' XM ', ' age ': ' + ', ' sex ': ' Male '}
Requst=info.pop (' asdfsadf ', ' none ')
Print (Requst)
None

Requst=info.get (' name1 ', ' none ')
Print (Requst)
None

#显示key和value
Print (Info.keys ()) #显示字典所有的key #for循环遍历的时候默认遍历key
Print (Info.values ()) #显示字典所有的value

info={' name ': ' XM ', ' age ': ' + ', ' sex ': ' Male '}
For n in Info.items (): #items take full dictionary
Print (n)

(' Name ', ' XM ')
(' Age ', ' 18 ')
(' Sex ', ' male ')

For Key,value in Info.items ():
Print (Key,value)

Name XM
Age 18
Sex male


info={' name ': ' XM ', ' age ': ' + ', ' sex ': ' Male '}
Dic=info.fromkeys ([' Name ', ' Ex ', ' age ', ' num '],1111111) #默认共享value
Print (DIC)
{' name ': 1111111, ' ex ': 1111111, ' age ': 1111111, ' num ': 1111111}

Print (dict (' name ', ' hehe '), (' Age ', ' one '), (' Sex ', ' male ')]) #生成字典



Dic=dict.fromkeys ([' Name ', ' Ex ', ' age ', ' num '],111) #生成字典, Dict called. Another way to do this is to manually create it directly.
Print (DIC)


info={' name ': ' XM ', ' age ': ' + ', ' sex ': ' Male '}
Print (info)
Dic={' A ': 1, ' B ': 2, ' name ': ' Hehe '}
Info.update (DIC)
Print (info)
# {' Name ': ' XM ', ' age ': ' + ', ' sex ': ' Male '}
# {' name ': ' hehe ', ' age ': ' + ', ' sex ': ' Male ', ' a ': 1, ' B ': 2}



19. Collection:
python=[' Alex ', ' Egon ', ' Yuanhao '
linux=[' Alex ', ' Egon ']
A=[]

For P in Python:
If P in Linux:
A.append (P)
Print (a)

Set: Also different elements of the composition, the collection is unordered, you can go to the weight, the collection of elements can be numbers, strings.
The elements within the collection must be immutable data types. The elements within the collection must be unique.
Use set to generate a collection. A collection cannot take a single value. Mainly used to do relational operations.
The method of the collection is temporarily not logged.

S1=set (' Heheh ')
Print (S1)
{' h ', ' e '}

The intersection is taking the public part of the two sets, and the set is taking all and taking the weight.

S1 = {1,2,4,5}
S2 = {3,2,6,5}

#交集
Print (S1 & S2)
#并集
Print (S1 | s2)
#差集
Print (S1-S2)
Print (S2-S1)
#对称差集
Print (s1 ^ s2)

#父集
Print (S1 >= S2)
#子集
Print (S2 <= s1)


Summary:
According to the number of storage worth:
Scalar/Atomic type: number, string
Container type: list, tuple, dictionary

By Variable immutable distinction:
mutable: List, dictionary
Immutable: Numbers, strings, tuples

Differentiate by Access order:
Direct access
Digital
Sequential access (sequence type) strings, lists, tuples
Key value access (mapping type) dictionary



20. Character encoding: Character encoding is a standard for converting encoding from one format to another.
The process of swiping in-memory characters to a hard disk is called encoding.
The process of reading a character from a file in a hard disk to memory is called decoding.
The format of the memory store character is in Unicode format.
The format of the hard disk storage character is utf-8 format

It is important to remember what format to use in what format to take.
The Python string defaults to Unicode format:

Unicode---> Encode---> bytes
Bytes---> Dedcode---> Unicode
Unicode character encoding can be cross-platform.

The default encoding for Python2 strings is bytes, and if you want to go to the format you need to precede the string with U
X=u ' What are you arguing about '?


21, the operation of the file:
Read () reads the file. Need to be aware of coding
ReadLine () reads a line
Readlins () reads all the lines of a file, forming a list


#读取文件的内容
f = open (' A.txt ', ' R ', encoding= ' utf-8 ')
Res=f.read ()
Print (res) #但是文件必须首先存在


#读取一行:
f = open (' A.txt ', ' R ', encoding= ' utf-8 ')
Res=f.readline ()
Print (res,end= ")
Print (res,end= ")
Print (res,end= ") #默认情况一行结束后会有 \ n, the normal display needs to add end="

#
With open (' A.txt ', ' R ', encoding= ' utf-8 ') as F:
Print (F.read ()) #该方法不需要关闭文件. However, if the A.txt file in the Chinese language, if not added encoding, read will error.

Remember to close the file when you are finished reading it. If you do not want to manually close remember to use the with open
Closed #标记文件是否已经关闭, rewritten by close ()

input = open (' Data ', ' R ')
#第二个参数默认为r
input = open (' Data ')
Read binary files
input = open (' Data ', ' RB ')



#写入文件
Write a text file
Output = open (' Data ', ' W ')
Write a binary file
Output = open (' Data ', ' WB ')
Append Write file
Output = open (' Data ', ' w+ ')
Write Multiple lines
File_object.writelines (list_of_text_strings)
Note that calling Writelines writes multiple rows at a higher performance than using write one-time writes.

#写入
f = open (' A.txt ', ' W ', encoding= ' utf-8 ')
F.write (' 111111111111\n ') #写入文件时, files that do not exist are automatically created, and write content is redirected to a file.
F.close ()
Modify the contents of the file, first open a copy of the file, and then read line by row substitution, and then delete the original file, the copy rename into the original file.


This article from "Man should self-reliance" blog, please be sure to keep this source http://nrgzq.blog.51cto.com/11885040/1947334

Python the next day

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.