笨方法学python 习题8

打印,打印

代码如下:(有报错)

formatter = '{} {} {} {}'

print(formatter.format(1,2,3,4))
print(formatter.format('one','two','three','four'))
print(formatter.format(True,False,True,False))
print(formatter.format(formatter,formatter,formatter,formatter))
print(formatter.format(
    'Try your',
    'Own text here'
    'Maybe a poem'
    'Or a song about fear'
))

报错如下

print(formatter.format(
IndexError: Replacement index 2 out of range for positional args tuple

代码修正后:

formatter = '{} {} {} {}'

print(formatter.format(1, 2, 3, 4))
print(formatter.format('one', 'two', 'three', 'four'))
print(formatter.format(True, False, True, False))
print(formatter.format(formatter, formatter, formatter, formatter))
print(formatter.format(
    'Try your',
    'Own text here',
    'Maybe a poem',
    'Or a song about fear',
))

输出:

1 2 3 4
one two three four
True False True False
{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}
Try your Own text here Maybe a poem Or a song about fear
进程已结束,退出代码0

Tips:

  1. 报错原因:‘Own text here’, ‘Maybe a poem’, ‘Or a song about fear’,后面丢失了“,”
  2. .format()是函数,调用函数,相当于执行format命令
  3. 给format传递4个参数,参数和formatter变量的{}相匹配,相当于参数传递给了format命令
  4. 在formatter调用format的结果生成新的字符串,{}被4个变量替换掉,得到结果
  5. True和False是python的关键字,加了引号就变成字符串了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值