Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存.[PEP-3101] This PEP proposes a new system for built-in string formatting operations, intended as a replacement for the existing '%' string formatting operator. 1.百分号…
使用百分号拼接字符串: 例如: msg='i am %s my hobby is...' %'abc' print(msg) 如果需要用2个%s呢?就使用括号例如: msg='I am %s my hobby is %s' %('abc','DDD') print(msg) 返回结果: i am abc my hobby is DDD %s是万能的,可以接收数字.字符串.列表缺点是可读性差 msg='I am %s my hobby is %s' %('abc',123) print(msg)…
# 格式化字符串: 在字符串前加上 f 或者 F 使用 {变量名} 的形式来使用变量名的值 year = 2020 event = 'Referendum' value = f'Results of the {year} {event}' print(f'Results of the {year} {event} \n', value) # : .3f 标示 保留前面的变量值/字面值3位小数 , 3d, 3 则是让盖子段成为最小字符宽度,在使列对齐时作用大 print(f'The value o…
#### 字符串格式化. # %s 代替任何的元素 (数字,字符串,列表··) print('I live %s crty' %'my') print('I live %s crty' %'[6,8,9]') I live my crty I live [6,8,9] crty # %s -- %( ) 可以代替多个元素 print('I live %s crty,prefer live %s country' %('your','my')) I live your crty,prefer li…
# %s可以接收一切 %d只能接收数字 msg = 'i am %s my hobby is %s' %('lhf','alex') print msg msg2 = 'i am %s my hobby is %d' %('lhf',1) print msg2 #打印浮点数 tpl ="percent %.2f" %99.976 #截取几位 print tpl tpl2 = "i am %(name)s age %(age)d" %{"name"…
在 Python 中字符串连接有多种方式,这里简单做个总结,应该是比较全面的了,方便以后查阅. 加号连接 第一种,通过+号的形式: >>> a, b = 'hello', ' world' >>> a + b 'hello world' 逗号连接 第二种,通过,逗号的形式: >>> a, b = 'hello', ' world' >>> print(a, b) hello world 但是,使用,逗号形式要注意一点,就是只能用于pr…
Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存. ----百分号 tpl = "i am %s" % "alex" #i am alex tpl = "i am %s age %d" % ("alex", 18) #i am alex age 18 tpl = "i am %(name)s age…