最近一直在学sentdex的python教学视频,其中里面提到了format 函数。 当时候我第一次遇到这个函数,我压根不明白{} 和 .format
之间的联系 。后来自己测试了一番,终于明白了个中的奥秘。
for ticker in tickers:
if not os.path.exists('stock_dfs/{}.csv'.format(ticker)):
df = web.DataReader(ticker, "yahoo", start, end)
df.to_csv('stock_dfs/{}.csv'.format(ticker))
else:
print('Already have {}'.format(ticker))
▌定义
花括号声明{}、用于渲染前的参数引用声明, 花括号里可以用数字代表引用参数的序号, 或者变量名直接引用。
▌例子
我随机的在wikipedia复制黏贴了一段话,然后将这段话以空格
分开。 最后的用for 遍历这段话并输出。
我发现了其实{}
的作用是显示任意内容i
。 但这个过程需要结合.format()来达到这个目的。
text = 'At the time of my writing this, Yahoo did not throttle me at all and I was able to run this all the way through without any '
flow = text.split(' ')
for i in flow:
print('this is a SPLIT with text: {}'.format(i))
▌输出
this is a SPLIT with text: At
this is a SPLIT with text: the
this is a SPLIT with text: time
this is a SPLIT with text: of
this is a SPLIT with text: my
this is a SPLIT with text: writing
this is a SPLIT with text: this,
this is a SPLIT with text: Yahoo
this is a SPLIT with text: did
this is a SPLIT with text: not
this is a SPLIT with text: throttle
this is a SPLIT with text: me
this is a SPLIT with text: at
this is a SPLIT with text: all
this is a SPLIT with text: and
this is a SPLIT with text: I
this is a SPLIT with text: was
this is a SPLIT with text: able
this is a SPLIT with text: to
this is a SPLIT with text: run
this is a SPLIT with text: this
this is a SPLIT with text: all
this is a SPLIT with text: the
this is a SPLIT with text: way
this is a SPLIT with text: through
this is a SPLIT with text: without
this is a SPLIT with text: any