python格式化字符串4种方法
出处:
def str_format():
context1 = '''there is a person, name: %s, age: %d, salary: %d''' %("lucy", 18, 2000)
'''
# %d %s %f %r
%d代表数字占位符,代表int整型,只能传递十进制整数
%s代表字符串占位符 , 代表string 字符串
%f 代表浮点,默认保留6位小数位,而第7位根据四舍五入取值;
%r 万能统配符 (可以将后面给的参数原样打印出来,带有类型信息)
'''
context2 = '''there is a person, name: %(name)s, age: %(age)d, salary: %(salary)d''' %dict(name="lili",age=19, salary=3000)
context3 = '''there is a person, name: {0}, age: {1}, salary: {2}'''.format("koko", 20, 4000)
# 3.6以后的版本,推荐使用
name, age, salary = "hanmeimei", 16, 6000
context4 = f'''there is a person, name is {name}, age is: {age}, salary is: {salary}'''
print(context1)
print(context2)
print(context3)
print(context4)
输出:
there is a person, name: lucy, age: 18, salary: 2000
there is a person, name: lili, age: 19, salary: 3000
there is a person, name: koko, age: 20, salary: 4000
there is a person, name is hanmeimei, age is: 16, salary is: 6000
' {} '.format()
# 插入变量
vqr = '我们'
var = '一个变量'
print(" {} 打印 {}".format(vqr, var))
>> 我们 打印 一个变量
#插入浮点数
var = 3.55555
print(" 打印 {}".format(var))
print(" 打印 {:.2f}".format(var))
>>打印 3.55555
>> 打印 3.56
匹配字符串中的ip地址
https://www.jb51.net/article/162641.htm
#匹配字符串中的ip地址
import re
string_ip = "is this 236.168.192.1 ip 12321"
result = re.findall(r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", string_ip)
if result:
print(result)
else:
print('re cannot find ip')
##string_IPv6="1050:0:0:0:5:600:300c:326b"
###匹配是否满足IPv6格式要求,请注意例子里大小写不敏感
##if re.match(r"^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}$", string_IPv6, re.I):
## print("IPv6 vaild")
##else:
## print("IPv6 invaild")
###提取IPv6,例子里大小写不敏感
##result = re.findall(r"(?<![:.\w])(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}(?![:.\w])", string_IPv6, re.I)
###打印提取结果
##print(result)
#####时间处理备忘
import time
###将字符串格式化成时间字符串
t1 = '2020/05/05 10:05:05' #创建一个字符串
t2 = time.strptime(t1,'%Y/%m/%d %H:%M:%S') # 将字符串格式化
#time.struct_time(tm_year=2020, tm_mon=5, tm_mday=5, tm_hour=10, tm_min=5, tm_sec=5, tm_wday=1, tm_yday=126, tm_isdst=-1)
t3 = time.strftime('%Y/%m/%d %H:%M:%S',t2) # 将 格式化过的字符串 格式化输出
#2020/05/05 10:05:05
print(t2,t3)
t11 = '2022-05-05 10:05:05'
t22 = time.strptime(t11,'%Y-%m-%d %H:%M:%S')
t33 = time.strftime('%Y-%m-%d %H:%M:%S',t22)
#2022-05-05 10:05:05
print(t22,t33)
#time.struct_time(tm_year=2020, tm_mon=5, tm_mday=5, tm_hour=10, tm_min=5, tm_sec=5, tm_wday=1, tm_yday=126, tm_isdst=-1) 2020/05/05 10:05:05
### 将字符串 转换成时间戳
#时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。可以用来加减计算,和比较大小
t2=time.mktime(time.strptime(t1,'%Y/%m/%d %H:%M:%S'))
#1588644305.0
t3 = t2 + 600
print(t2)
### 将时间戳 转换成时间字符串
t4 = time.strftime('%Y/%m/%d %H:%M:%S',time.localtime(t3))
t5 = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(t3))
print(t4,t5)
#2020/05/05 10:15:05 2020-05-05 10:15:05
#####随机生成混合字符串(字母 数字 符合等混合)
import random
import string
##生成一个混合字符串
name = ''.join(random.sample(string.ascii_letters + string.digits + " ------___", random.randint(1,5))) #### random.randint(1,5) (1,5)表示字符串长度随机范围 1到5个
###生成多个随机混合字符串
ww = [x for y in range(1,6) for x in [''.join(random.sample(string.ascii_letters + string.digits + " ------___", random.randint(3,5)))]]
##备注:for x in [ ] 中括号里面 要填完整的生成语句。不能直接引用 name。不然输出都是一样的。
## for y in range(1,6) 小括号决定了 要生成几个
print(ww)
#############生成一组随机数:
################# 生成一组 随机浮点数
a = [x for y in range(0,10) for x in [random.randint(0,10000) / 100 ]]
## for y in range(0,10) 控制生成的列表的元素个数
### [random.randint(0,10000) / 100 ] 控制浮点数取值范围
a = [x for y in range(0,100) for x in [round(random.uniform(0,100),2)]]
##### [round(random.uniform(0,100),2)] (0,100)取值范围 2 是保留小数点2位
################ 生成一组随机整数
a = [x for y in range(0,10) for x in [random.randint(0,100)] ]
##########windows下调用其他exe或bat
例如同目录下有个 /bin/do.exe
impport os
os.system('{} 0'.format(os.getcwd()+'\\bin\\do.exe'))
##### 合并列表
a = [1,2]
b = [3,4]
c = [a,b]
方法一:
d = a+b
方法二:
e = []
e.append(a)
e.append(b)
方法三:
print(c,d,e)
###》 [[1, 2], [3, 4]] [1, 2, 3, 4] [[1, 2], [3, 4]]
方法一 和方法三 效果是一样的
*** Remote Interpreter Reinitialized ***
[[1, 2], [3, 4]] [1, 2, 3, 4] [[1, 2], [3, 4]]
>>>
## 判断列表与列表 包含关系
#方法一
#创建一个函数,在函数里循环判断b列表的元素是否在a,如果不在则直接终止循环并函数
#返回假,如果循环b的元素全部都在a,则函数返回真
print("方法一")
a = [1, 2, 3, 4]
b = [2 , 3]
def bina():
for bb in b:
if bb in a:
pass
else:
return False
return True
if bina():
print("a 包含 b")
else:
print("a 不包含 b")
#方法二:
#使用列表推导式,遍历b的元素判断是否在a,如果在则添加到新列表c
#判断c和b是否相同
print("方法二")
c = [x for x in b if x in a]
print(c)
if b == c:
print("a 包含 b")
else:
print("a 不包含 b")
#方法三
#使用内置的all函数,判断从b中遍历出的元素是否在a,如果所有的判断都是真,则返回真
print("方法三")
result = all(elem in a for elem in b)
if result:
print("a 包含 b")
else:
print("a 不包含 b")
#方法四
#使用列表推导式,如果b的元素不在a则列表d添加一个FALSE,
##print("方法四")
d = [False for c in b if c not in a]
print(d)
if d:
print('a 不包含 b 的所有元素!')
else:
print('a 包含 b 的所有元素!')
######## 文件读写
##################文本读写
#将文件中的内容以字符串的形式输出
def read_f():
with open('.\1.txt','r') as f:
#将文件中的内容以字符串的形式输出
s = f.read()
return s
#读取一行内容;
def read_f():
with open('.\1.txt','r') as f:
s = f.readline()
return s
#读取所有行,以列表的方式返回;
def read_f():
with open('.\1.txt','r') as f:
r = f.readlines()
s=[x.strip() for x in r ]
return s
n1 = '''wwwww
wwwwwww'''
def write_f(n1):
with open('.\serial_tool.txt','w') as f:
#写字符串
f.write(n1)
n1 = '''wwwww
wwwwwww'''
n2 = ['1','2']
def write_f(n1,n2):
with open('.\serial_tool.txt','w') as f:
#写字符串或者列表
f.writelines(n1)
f.writelines(n2)
n1 = [1,2,5]
def write_f(n1):
with open('.\serial_tool.txt','w') as f:
#写列表
for n2 in n1:
f.write(str(n2 )+ '\n')