06 -Python入门- Lesson6 脚本

06 Python入门 Lesson6 脚本

9.在脚本中接受原始输入

这里出现了个有点奇怪的print函数,就是上节讲到

name = input("Enter your name: ")
print("Hello there, {}!".format(name.title()))

Plus.格式化字符串

课程中初次见面

有点奇怪啊,不就是让用户输入个名字,不是应该这样的么?

name = input("Enter your name: ")
print("Hello there, ", name, "!")

对的,实际上输出是一样的,后面这个我们比较熟悉,把字符和变量串在一起输出。但是观察下上下对比,是不是上面的这个比较简单呢?这种新的方法叫做:**print格式化字符串。**大家对比观察一下,其实就是在print里面放了个{},并在后面加了个.format(name.title)。这个语句的意思是,打印到{}的时候,把后面这个.format()里的东西打印出来,name.title就是把输入的name的第一个字母改为大写。默认{} {} {}…会按照后面.format(a, b, c)来替换,但也可以指定。比如{0}指定的是a,{1}指定的是b,以此类推。举个例子就知道了:

##format methord
print('---test1:---')
print('I am lucky to eat {} {} {} {}!'.format(4,'eggs', 1, 'spam'))
print('---test2:---')
print('I am lucky to eat {2} {1} {3} {0}!'.format(4,'eggs', 1, 'spam'))
print('---test3:(option)---')
print('I am lucky to eat {2:.2f} {1} {3} {0}!'.format(4,'eggs', 1, 'spam'))
print('---test4:(option)---')
print('I am lucky to eat {2:.2f} {1:#^20} {3} {0}!'.format(4,'eggs', 1, 'spam'))

输出是这样的:其中test3,4是更为复杂的应用,感兴趣的话看这两个链接:https://blog.csdn.net/i_chaoren/article/details/77922939
https://www.cnblogs.com/wilber2013/p/4641616.html

---test1:---
I am lucky to eat 4 eggs 1 spam!
---test2:---
I am lucky to eat 1 eggs spam 4!
---test3:(option)---
I am lucky to eat 1.00 eggs spam 4!
---test4:(option)---
I am lucky to eat 1.00 ########eggs######## spam 4!

print中输出变量的简单方法

print再扩展一点,如果看到这样的家伙 + variable + ,是一种在字符串中加变量的方法,其实和逗号分隔是等价的:

print('hi ' + name + ' !')
print("hi " + name + " !")
print('hi', name, '!')
print("hi", name, "!")
#这4个的输出都是一样的:(注意下代码前后的空格是不一样的,所以前面的也会用到)
hi handsome !

需要处理复杂的就print(“xxx{}” .format()) (ps:还有一种写法是print(“xx%zz” % ())大家知道就可以了)。详细的带入列表和字符串的方法:https://stackoverflow.com/questions/17153779/how-can-i-print-variable-and-string-on-same-line-in-python

这一节后面还有个eval是把用户输入的内容当作python代码处理。扩展下也可以这样使用,把str字符转化为相应的内容(>>>是输入的代码),大家注意a和b的type是不一样的:

>>>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值