|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
零基础入门学习Python 第十七讲课后题:
1. 编写一个函数,利用欧几里得算法(脑补链接)求最大公约数,例如 gcd(x, y) 返回值为参数 x 和参数 y 的最大公约数。
我写了一个为什么总是提示错误
之后是我的代码, 如何定义Python里的format, 有点不太明白,希望高手指点
本帖最后由 Twilight6 于 2020-5-18 07:42 编辑
format 是格式化的一种,它的格式化的格式是:- ' {} {}'.format(替换字段1,替换字段2)
复制代码
第一种使用情况:
在你 { } 中没有设置参数时,format默认顺序是和 ( ) 里的顺序一一对应来进行替换 如:
- name = 'Python'
- age = 18
- "hello, {}. you are {}?".format(name,age)
- >>>'hello, Python. you are 18?'
复制代码
第二种使用情况是通过位置参数索引:
- name = 'Python'
- age = 18
- "hello, {1}. you are {0}?".format(name,age)
- # 对应format后面的() 中的位置参数 可以不按顺序
- >>>'hello, 18. you are Python?'
复制代码
第三种情况使用关键字参数:
直接使用关键字方法:
- name = 'Python'
- age = 18
- "hello, {name1}. you are {age1}?".format(age1=age,name1=name)
- >>>'hello, Python. you are 18?'
复制代码
使用**字典关键字参数方法:
- person = {"name":"Python","age":18,"temp":"cool"}
- "hello, {temp}. you are {age}? {name}".format(**person)
- >>>'hello, cool. you are 18? Python'
复制代码
第四种情况关键字、位置参数混用(非常不建议这样用):
- name = 'Python'
- age = 18
- "hello, {name1}. you are {0}?".format(age,name1=name)
- >>>'hello, Python. you are 18?'
复制代码
但是如果混用要记住一点,formar后面的( )里的使用关键字参数的位置必须在使用位置参数的位置之后
正确例:
- print("hello, {name1}. you are {0}? {temp}".format(age,temp='cool',name1=name))
- # age是使用位置参数定位的所以要放再 temp、name1 使用关键字参数之前
复制代码
错误例:
- print("hello, {name1}. you are {0}? {temp}".format(temp='cool',age,name1=name))
- # age 在位置参数之后导致报错
复制代码
这边附带自己整理的笔记:
3种格式化用法
链接:http://note.youdao.com/noteshare ... C2183317BF11F4166E6
如果帮助到你了,记得给个最佳哦~
|
-
-
|