Python 3神一样的字符串格式

一、%

在%左边指定一个字符串(格式字符串),并在右边指定要设置其格式的值。

>>> format = "Hello, %s. %s enough for ya?"
>>> values = ('world', 'Hot')
>>> format % values
'Hello, world. Hot enough for ya?'

 

二、模板字符串

>>> from string import Template
>>> tmpl = Template("Hello, $who! $what enough for ya?")
>>> tmpl.substitute(who="Mars", what="Dusty")
'Hello, Mars! Dusty enough for ya?'

 

三、每个替换字段都用花括号括起

       1、替换字段没有名称或将索引用作名称

            >>> "{}, {} and {}".format("first", "second", "third")
           'first, second and third'

      2、索引、无需按顺序排列

           >>> "{0}, {1} and {2}".format("first", "second", "third")
          'first, second and third'

          >>> "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to")
          'to be or not to be'

      3、有命名字段

         >>> from math import pi
         >>> "{name} is approximately {value:.2f}.".format(value=pi, name="π")
         'π is approximately 3.14.'  

 

        在Python 3.6中,如果变量与替换字段同名,还可使用一种简写。在这种情况下,可使用f字符串——在字符串前面加上f

        >>> from math import e
        >>> f"Euler's constant is roughly {e}."
        "Euler's constant is roughly 2.718281828459045."   

        等价于

        >>> "Euler's constant is roughly {e}.".format(e=e)
        "Euler's constant is roughly 2.718281828459045."

-----------------------

以上种种让我想起了Linux的shell,看来Python可能还真是个能用来写脚本的货。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值