python学习:format新写法
介绍
format对于我们来说是经常使用的,无论是输出给用户,还是拼接字符串,非常常见。今天无意中看到一种format的写法,有点意思,而且很方便。
使用
常用的format,我们会是下面几种使用方法。
1.指定类型
>>> 'hello, %s' % 'world'
'hello, world'
2. 指定名字
>>> 'hello, {name}'.format(name='world')
'hello, world'
3. 当然也能指定进制
>>> 'there is 0x{test:x}'.format(test=10)
'there is 0xa'
有很多种的,我就不一一列举出来了。
新方法
我们经常会有这种要求,拼接字符串,当然也能用上面的方法,不过我这边还有更好玩的。
def func(a):
b = "hello"
return b+","+a
如上面的例子。
这个时候,我们可以有下面几种解决方案 。
跟ruby类似
还是上面那个例子
def func(a):
b = 'hello'
return f'{b}, {a}'
>>> func("bbb")
'hello, bbb'
这样是不是很干净,跟ruby很类似。
当然也能用在print上面,类似。
>>> a = '111'
>>> print(f'hello, {a}')
hello, 111
2. 使用template
>>> from string import Template
>>> t = Template('Hello, $a!')
>>> t.substitute(a='world')
'Hello, world!'
这种我建议用在比较,拼接的字符串,很多地方用到,可以专门把那些字符串写在一个地方,统一管理。
总结
这两个方法我感觉还行,挺好用的。