栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

字符串格式选项:利弊

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

字符串格式选项:利弊

为什么
format()
%
字符串操作更灵活

我认为您应该真正使用

format()
of的方法
str
,因为它是格式化字符串的首选方法,并且将来可能会替换字符串格式化操作。

此外,它还具有一些非常好的功能,还可以 将基于位置的格式与基于关键字的格式相结合

>>> string = 'I will be {} years and {} months on {month} {day}'>>> some_date = {'month': 'January', 'day': '1st'}>>> diff = [3, 11] # years, months>>> string.format(*diff, **some_date)'I will be 3 years and 11 months on January 1st'

即使以下情况也可以使用:

>>> string = 'On {month} {day} it will be {1} months, {0} years'>>> string.format(*diff, **some_date)'On January 1st it will be 11 months, 3 years'

还有另一个理由支持

format()
。由于它是一种方法,因此可以像下面的示例一样作为回调传递:

>>> data = [(1, 2), ('a', 'b'), (5, 'ABC')]>>> formatter = 'First is "{0[0]}", then comes "{0[1]}"'.format>>> for item in map(formatter, data):    print itemFirst is "1", then comes "2"First is "a", then comes "b"First is "5", then comes "ABC"

它比字符串格式化操作灵活得多吗?

有关操作和方法之间的比较,请参见文档页面上的更多示例。

%``.format()

将基于元组的
%
字符串格式与基于字典的字符串格式进行比较

通常,有以下 三种调用

%
字符串操作的方式(是, 三个 ,不是 两个 ):

base_string % values

它们的类型不同

values
(这是的内容的结果
base_string
):

  • 它可以是一个

    tuple
    ,然后按照它们在元组中出现的顺序一一替换,

    >>> 'Three first values are: %f, %f and %f' % (3.14, 2.71, 1)

    ‘Three first values are: 3.140000, 2.710000 and 1.000000’

  • 它可以是

    dict
    (字典),然后根据关键字替换它们,

    >>> 'My name is %(name)s, I am %(age)s years old' % {'name':'John','age':98}

    ‘My name is John, I am 98 years old’

  • 如果

    base_string
    包含应该插入值的单个位置,则它可以是单个值:

    >>> 'This is a string: %s' % 'abc'

    ‘This is a string: abc’

它们之间存在明显的区别,并且这些方法无法合并(与

format()
如上所述的能够合并某些功能的方法相反)。

但是有些东西 仅特定于基于字典的字符串格式化操作 ,而在其余三种格式化操作的类型中则不可用。这是 一种以简单的方式用实际变量名 替换
说明 符的功能

>>> name = 'John'>>> surname = 'Smith'>>> age = 87# some pre goes here>>> 'My name is %(surname)s, %(name)s %(surname)s. I am %(age)i.' % locals()'My name is Smith, John Smith. I am 87.'

仅作记录:当然可以通过

format()
如下解包字典来轻松地替换上面的内容:

>>> 'My name is {surname}, {name} {surname}. I am {age}.'.format(**locals())'My name is Smith, John Smith. I am 87.'

还有其他人有什么想法可能是一种特定于字符串格式化操作的功能,而不是另一种吗?听到它可能会很有趣。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/651796.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号