加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 创业 > C语言 > 正文

20200923-Python学习笔记4

发布时间:2020-12-15 02:13:39 所属栏目:C语言 来源:网络整理
导读:用%实现格式化 常见的占位符 %s : 字符串%d : 整数%f : 浮点数%x : 十六进制整数 % 运算符就是用来格式化字符串的。在字符串内部,%s示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以

用%实现格式化

常见的占位符

%s :   字符串
%d :    整数
%f :    浮点数
%x :    十六进制整数

%运算符就是用来格式化字符串的。在字符串内部,%s示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。

>>> 'Hello,%s' % 'word'
'Hello,word'
>>> 'Hello,%s,you have $%d.' % ('kk',999999)
'Hello,kk,you have $999999.'
>>>

%d 整数 和 %f 浮点数? 举例:

>>> print('%2d-%02d' % (3,1))
 3-01
>>> print('%d-%02d' % (3,1))
3-01
>>> print('%d-%0d' % (3,1))
3-1
>>> print('%.f' % 3.1415926)
3
>>> print('%.3f' % 3.1415926)
3.142
>>> print('%.2f' % 3.1415926)
3.14
>>>
>>> print('%d-%13d' % (3,1))
3- 1
>>> print('%d-%03d' % (3,1))
3-001
>>> print('%d-%9d' % (3,1))
3- 1
>>> print('%d-%09d' % (3,1))
3-000000001
>>>

转义,用%% 表示 %

>>> '%d %%' % 9
'9 %'
>>>

format():格式化字符串函数,用{} : 代替 %? ? ? ? ? 用传入的字符串依次代替{0}{1}{2},或者直接指定内容

>>> "{}{}".format("hello","word")
'helloword'
>>> "{0} {1}".format("hello","word")
'hello word'
>>> "{0} {1}".format("word","hello")
'word hello'
>>> "{1} {0} {1}".format("hello","word")
'word hello word'
>>>

>>> 'hello,{0},成绩下降了 {1:.1f}%'.format('小李',9.378)
'hello,小李,成绩下降了 9.4%'
>>>
>>> print("网站名:{name},地址{url}".format(name="菜鸟",url="www.cainiao.com"))
网站名:菜鸟,地址www.cainiao.com
>>>

f-string? ?函数??

>>> name = " 269 "
>>> f"hello,my name is {name}"
'hello,my name is  269 '
>>> number = 3
>>> f"i have {number} books"
'i have 3 books'
>>> r = 4.6
>>> s = 3.16 * r **2
>>> print(f'the area of a circle with radius {r} is {s:.2f}')
the area of a circle with radius 4.6 is 66.87
>>>

{r}被变量r的值替换,{s:.2f}被变量s的值替换,并且:后面的.2f指定了格式化参数,保留两位小数

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读