1、去除转义使用r
比如:\n表示换行,如果直接在代码中直接使用的话,会被认为是换行,那么如果不想让Python解释成换行,让其保留\n原义,那么可以在前面加上r

s1 = '123456\n'
s2 = r'123456\n'
print(s1)
print(s2)
print('********')

运行结果:

123456

123456\n
********

2、编解码

decode()是解码:将指定的编码方式---->unicode编码方式,比如:str1.decode(‘utf-8’),将utf-8编码方式的str1解码成Unicode编码方式。
encode()是编码:将Unicode的编码方式—》指定的编码方式,比如str1.encode(‘utf-8’),字符串在Python3中的默认编码方式为utf-8编码方式,Python2中默认为Unicode编码方式,可以通过sys.getdefaultencoding()这个方法获取当前文件的编码方式,执行上面的编码之后,str的编码方式就是utf-8编码方式了。

3、zfill()方法

import random
hour = random.randint(0,23)
hour = str(hour).zfill(2)
print(hour)

运行结果:

02

从上面的运行结果可以看到,就是对字符串进行前面补零操作。它是字符串的一个方法。通常在时间的定义的时候会使用到。

import random
hourA = random.randint(0,23)
hourA = str(hourA).zfill(2)
second = random.randint(0,59)
second = str(second).zfill(2)
time = hourA + ':' + second
print(time)

运行结果

23:46