table of Contents
- Import module Python
- Set Python module search path There are several ways how to use
- Connection between various types of variable values
- Decimal, binary, octal and conversion between hex
- Change the first letter of a string of case
Import module 01. Python
Import module
import math #模块名
print(math.sin(1.23)) #要用math.
from math import cos, tan #成员名
from math import *
print(cos(1.23)) #不用math.
Alias as
import math as m
print(m.sin(20))
#print(math.sin(20))将出错
form math import cos as c
print(c(30))
#print(cos(30))将出错
to sum up
02. Set Python module search path There are several ways how to use
Arrangement Python module search path
1. Set PYTHONPATH environment variable (permanent)
2. Add .pth file (permanent)
cd python3.7
cd site-packages
vi abc.pth
#然后添加路径
After scanning the file will be added to sys.path in .pth
3. (Temporary) by setting the path sys.path
4. If PyCharm, may be provided directly to the search path (permanent)
Cancel
set the search path in the console
summary
03. plurality of connection between the various types of variable values
How to connect between the strings and the string
#字符串与字符串之间连接的方式有 5 种
##第一种:+ (加号)
s1 = 'Hello'
s2 = 'World'
s = s1 + s2
#第二种:直接连接
s = 'Hello''World'
#第三种:用,(逗号)连接,标准输出的重定向
from io import StringIO
import sys
old_stdout = sys.stdout #保存标准输出
result = StringIO() #定义一个String对象,将标准输出放到里面
sys.stdout = result
print('hello', 'world') #此时print不会在控制台上显示
sys.stdout = old_stdout #恢复标准输出
result_str = result.getvalue()
print('用逗号连接:', result_str)
#第四种:格式化
s = '%s %s' % (s1, s2)
print('格式化:', s)
#第五种:join
s = ' '.join([s1, s2])
How to connect between the strings and the string of non-
#第一种:+
n = 20
s = s1 + str(n) #将非字符串转换成字符串
#第二种:格式化
s = '%s %d' % (s1, n)
#第三种:重定向
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print('hello', 20, sep='*') #*号分割
sys.stdout = old_stdout
result_str = result.getvalue()
print('用逗号连接:', result_str)
#第三题
s1 = 'hello'
class MyClass:
def __str__(self):
return 'This is MyClass'
my = MyClass()
s = s1 +str(my)
print(s)
to sum up
04. decimal, binary, octal and conversion between hex
How to represent different binary
#十进制
n1 = 1234
#二进制
n2 = 0b11101
#八进制
n3 = 0o127
#十六进制
n4 = 0xf153
#o, b, x都不区分大小写
Conversion between hex
#十进制转二进制
print(bin(20)) #类型为str
#二进制转十进制
print(int('10110', 2)) #类型为int
#十六进制转十进制
print(int('f35ae', 16)) #加不加0x都行
#十进制转十六进制
print(hex(54321))
#十六进制转二进制
print(bin(0xf21a))
#二进制转十六进制
print(hex(0b1100110))
#十进制转八进制
print(oct(542))
#八进制转十进制
print(int('3213', 8))
#输出任然是十进制
print(0b11101 * 0x2146 * 0o1245 * 13)
to sum up
05. change the case of the first letter of a string
Modified string of letters
#修改字符串首字母大小写
s1 = 'hello'
print(s1.capitalize())
#str类型是不可修改的s1[0] = 'H'是错误的
#拆分字符串
s2 = s1[:1] + s1[1].upper() + s1[2:]
#第二题:
s3 = 'hello world'
a = s3.split(' ')
new_str = f'{a[0].capitalize()} {a[1].capitalize()}'
to sum up