Python common usage one

1, print() function

The print() function can not only output the content to the screen, but also output to the specified file. code show as below:

fp = open(r'e:\\tb.txt','a+')
print("成功的唯一秘诀,就是坚持最后一分钟",file = fp)
fp.close()

The essence of print(obj) is to call sys.stdout.write(obj+'\n')

# 两者等价
sys.stdout.write('hello'+'\n')
print('hello')

Here sys.stdout is the standard output stream in python. This standard output stream is mapped to the window that opens the script by default, so our print operation will print the characters to the screen. Since sys.stdout is mapped to the window that opens the script by default, can this mapping relationship be modified?

The answer is yes, we can redirect our printing operations to other places, such as specific files, by modifying this mapping relationship.


print() redirect to a specified file

The method is to assign a value to sys.stdout and modify its point

import sys
sys.stdout = open('test.txt','w')
print 'Hello world'

2. The parentheses () in python: represent the data type of tuple tuple, which is an immutable sequence.

>>> tup = (1,2,3)    
>>> tup    
(1, 2, 3)    

3. The brackets [] in python represent the list data type:

>>> list('python')    
['p', 'y', 't', 'h', 'o', 'n']

4, python curly braces {} curly braces: represent the dic t dictionary data type, and the dictionary is composed of key pair value groups. The colon':' separates the key and value, and the comma',' separates the group. The method of creating with braces is as follows:

>>> dic={'jon':'boy','lili':'girl'}    
>>> dic    
{'lili': 'girl', 'jon': 'boy'}    
>>>

5. Keywords in and is

in关键字用于判断是否包含在指定的序列中。is关键字用于判断两个标识符是不是用于同一个对象

5 in (1,2,5,8)

True

5 in (1,2,8,10)

False

a = 20

b = 20

a is b

True

6. Get non-contiguous sequence

#列表

x1 = [1,2,3,4,5,6,7]

print("列表")

print(x1 [1:5:1])

print(x1 [1:5:2])

python 的切片提供了第三个参数:步长。默认情况下步长为“1”。

7, sequence addition

x1 = [1,2,3] + [4,5,6,7]
print("列表")
print(x1)

8, the sequence is repeated

x1 =[1,2,3,]*5
print(x1)

Operation result: [1,2,3,1,2,3,1,2,3]

9. Membership

#coding:utf8

print(5 in [1,2,3,4,5,6,7])
print("hi" in [1,2,3,4,5,6,7])

10, the sum of the minimum and maximum lengths

#coding:utf8

x1 = [1,2,3,4,5,6,7]
print(len(x1))
print(min(x1))
print(max(x1))
print(sum(x1))

Guess you like

Origin blog.csdn.net/wzhrsh/article/details/106344309