摘要:
- 关于Python中如何将某个表达式的值嵌入到字符串中,涉及到的内容为格式化字符串
- 关于Python中for循环一个有趣的事(陷阱?)
一、Python中-格式化字符串的用法总结
有时候,可能会用到将某个表达式的值嵌入到字符串中,例如在生成某些Excel表格需要添加生成该表格的时间戳:
import pandas as pd
import time
tm = time.strftime('%Y%m%d%H%M%S')
dic = {'A': [1, 2, 3, 4]}
df = pd.DataFrame(dic)
# 需要输出以下xlsx文件,但是需要加入时间戳:xxx_20190101100000.xlsx
当然了,最直接的方法就是,字符串拼接:
df.to_excel(r'xxx_' + str(tm) + '.xlsx', index=False)
以上是最简单的,还有其他的方法:
- %-formatting
df.to_excel(r'xxx_%s.xlsx'%tm, index=False)
- str.format()方法
df.to_excel(r'xxx_{}.xlsx'.format(tm), index=False)
- f-string方法(推荐)
df.to_excel(rf'xxx_{tm}.xlsx, index=False)
当然了,关于%-formatting, str.format(), f-strings 用法肯定没有这么简单,更复杂更多元的用法可以参考
https://www.cnblogs.com/meilong/p/Python-ge-shi-hua-zi-fu-chuan.html
str.format():https://docs.python.org/3/library/string.html#formatstrings
str.format():https://blog.csdn.net/jpch89/article/details/84099277
f-strings:https://docs.python.org/3/reference/lexical_analysis.html#f-strings
二、关于for循环有趣的事
lst = []
for i in range(5):
lst.append(lambda x: x*i)
那猜一猜:
lst[1](1) = 1 ?
lst[2](2)=4 ?
那我们来打印一下:
print(f'lst[1](1):{lst[1](1)}') # lst[1](1)=4
print(f'lst[2](2):{lst[2](2)}') # lst[2](2)=8
为什么出现这样的情况?
首先我们知道,lst中实际存储的各个元素是一个个函数对象:
![b0e7d190a41c6f7cf20bb23fbcd3b668.png](https://img-blog.csdnimg.cn/img_convert/b0e7d190a41c6f7cf20bb23fbcd3b668.png)
那当我们去调用各个函数的时候,Python解释器会去寻找各个变量所代表的值:
在打印lst[1](1),才会去寻找 x的值,与i的值 ,此时 x的值为1,那i的值到底是多少呢?
是1吗?在解决这个问题之前,那么接下来看另外一个例子:
for i in range(5):
pass
print(i)
那此时 i 等于多少?i = 4
![1ec15a11c58d0c0d5ff44118b99a3c27.png](https://img-blog.csdnimg.cn/img_convert/1ec15a11c58d0c0d5ff44118b99a3c27.png)
也就是说,在Python中,当 for 循环结束时,其 i 并不会被删除,而是会保存最后一个i的值即4。
那回到上面的例子中,即当for 循环结束时,i 也不会被删除,而保存的值为i=4 ,即当计算lst[1](1), lst[2](2)时,实际上i的值都为4,那么结果自然而然为
lst[1](1) = 4 * 1 = 4
lst[2](2) = 4 * 2 = 8
上面的例子,我们可以改写一下,可以清楚的看到在调用函数时,i的值到底是多少
lst = []
def calculate(x):
print('打印一下i的值:', i)
return x*i
for i in range(5):
lst.append(calculate)
print(f'lst[1](1){lst[1](1)}')
print(f'lst[2](2){lst[2](2)}')
![a518cfb91cc54133e29ab83d07d4edcf.png](https://img-blog.csdnimg.cn/img_convert/a518cfb91cc54133e29ab83d07d4edcf.png)
那如何把i的值实时的传递给函数呢?只需要将i 传递给函数,作为局部变量保存下来即可:
lst = []
for i in range(5):
lst.append(lambda x, i=i: x*i)
print(f'lst[1](1){lst[1](1)}')
print(f'lst[2](2){lst[2](2)}')
此时,lst[1](1)就等于1,lst[2](2)就等于4了
![a16242c0746e5200df67c39bf07554a4.png](https://img-blog.csdnimg.cn/img_convert/a16242c0746e5200df67c39bf07554a4.png)
参考:
8. Compound statementsdocs.python.org文笔不好,水平有限,若有错误,欢迎指正与交流