【练习】
   #练习1:format
print(format(3.44444,'.3e'))  #3.444e+00

#练习2:findall() & finditer()
import re
content = '''email:12345678@163.com
email:2345678@163a.com
email:345678@163.com'''
#没有分组
result_finditer = re.finditer(r'\d+@\w+.com',content)
print(result_finditer) #<callable_iterator object at 0x0000000001EA3C50>
for i in result_finditer:
# print(i.group(0))
#上方句子等价于下面的
print(i.group()) '''
12345678@163.com
2345678@163a.com
345678@163.com
'''
result_findall = re.findall(r'\d+@\w+.com',content)
print(result_findall) #['12345678@163.com', '2345678@163a.com', '345678@163.com']
for i in result_findall:
print(i)
'''
12345678@163.com
2345678@163a.com
345678@163.com
'''
print('**************')
#有分组
result_finditer = re.finditer(r'(\d+)@(\w+).com',content)
for i in result_finditer: #print(i.group())
'''
12345678@163.com
2345678@163a.com
345678@163.com
'''
#print(i.group(0))
'''
12345678@163.com
2345678@163a.com
345678@163.com
'''
#print(i.group(1))
'''
12345678
2345678
345678
'''
#print(i.group(2))
'''
163
163a
163
''' result_findall = re.findall(r'(\d+)@(\w+).com',content)
print(result_findall) #[('12345678', '163'), ('2345678', '163a'), ('345678', '163')]
for i in result_findall:
print(i)
'''
('12345678', '163')
('2345678', '163a')
('345678', '163')
'''
 
 
 

PyFormat Using % and .format() for great good!

Python has had awesome string formatters for many years but the documentation on them is far too theoretic and technical. With this site we try to show you the most common use-cases covered by the old and new style string formatting API with practical examples.

All examples on this page work out of the box with with Python 2.7, 3.2, 3.3, 3.4, and 3.5 without requiring any additional libraries.

Further details about these two formatting methods can be found in the official Python documentation:

If you want to contribute more examples, feel free to create a pull-request on Github!

Table of Contents:

  1. Basic formatting
  2. Value conversion
  3. Padding and aligning strings
  4. Truncating long strings
  5. Combining truncating and padding
  6. Numbers
  7. Padding numbers
  8. Signed numbers
  9. Named placeholders
  10. Getitem and Getattr
  11. Datetime
  12. Parametrized formats
  13. Custom objects

Basic formatting

Simple positional formatting is probably the most common use-case. Use it if the order of your arguments is not likely to change and you only have very few elements you want to concatenate.

Since the elements are not represented by something as descriptive as a name this simple style should only be used to format a relatively small number of elements.

Old

'%s %s' % ('one', 'two')

New

'{} {}'.format('one', 'two')

Output

one two

Old

'%d %d' % (1, 2)

New

'{} {}'.format(1, 2)

Output

1 2

With new style formatting it is possible (and in Python 2.6 even mandatory) to give placeholders an explicit positional index.

This allows for re-arranging the order of display without changing the arguments.

This operation is not available with old-style formatting.

New

'{1} {0}'.format('one', 'two')

Output

two one

Value conversion

The new-style simple formatter calls by default the __format__() method of an object for its representation. If you just want to render the output of str(...) or repr(...) you can use the !s or !r conversion flags.

In %-style you usually use %s for the string representation but there is %r for a repr(...) conversion.

Setup

class Data(object):

    def __str__(self):
return 'str' def __repr__(self):
return 'repr'

Old

'%s %r' % (Data(), Data())

New

'{0!s} {0!r}'.format(Data())

Output

str repr

In Python 3 there exists an additional conversion flag that uses the output of repr(...) but uses ascii(...) instead.

Setup

class Data(object):

    def __repr__(self):
return 'räpr'

Old

'%r %a' % (Data(), Data())

New

'{0!r} {0!a}'.format(Data())

Output

räpr r\xe4pr

Padding and aligning strings

By default values are formatted to take up only as many characters as needed to represent the content. It is however also possible to define that a value should be padded to a specific length.

Unfortunately the default alignment differs between old and new style formatting. The old style defaults to right aligned while for new style it's left.

Align right:

Old

'%10s' % ('test',)

New

'{:>10}'.format('test')

Output

      test

Align left:

Old

'%-10s' % ('test',)

New

'{:10}'.format('test')

Output

test      

Again, new style formatting surpasses the old variant by providing more control over how values are padded and aligned.

You are able to choose the padding character:

This operation is not available with old-style formatting.

New

'{:_<10}'.format('test')

Output

test______

And also center align values:

This operation is not available with old-style formatting.

New

'{:^10}'.format('test')

Output

   test   

When using center alignment where the length of the string leads to an uneven split of the padding characters the extra character will be placed on the right side:

This operation is not available with old-style formatting.

New

'{:^6}'.format('zip')

Output

 zip  

Truncating long strings

Inverse to padding it is also possible to truncate overly long values to a specific number of characters.

The number behind a . in the format specifies the precision of the output. For strings that means that the output is truncated to the specified length. In our example this would be 5 characters.

Old

'%.5s' % ('xylophone',)

New

'{:.5}'.format('xylophone')

Output

xylop

Combining truncating and padding

It is also possible to combine truncating and padding:

Old

'%-10.5s' % ('xylophone',)

New

'{:10.5}'.format('xylophone')

Output

xylop     

Numbers

Of course it is also possible to format numbers.

Integers:

Old

'%d' % (42,)

New

'{:d}'.format(42)

Output

42

Floats:

Old

'%f' % (3.141592653589793,)

New

'{:f}'.format(3.141592653589793)

Output

3.141593

Padding numbers

Similar to strings numbers can also be constrained to a specific width.

Old

'%4d' % (42,)

New

'{:4d}'.format(42)

Output

  42

Again similar to truncating strings the precision for floating point numbers limits the number of positions after the decimal point.

For floating points the padding value represents the length of the complete output. In the example below we want our output to have at least 6 characters with 2 after the decimal point.

Old

'%06.2f' % (3.141592653589793,)

New

'{:06.2f}'.format(3.141592653589793)

Output

003.14

For integer values providing a precision doesn't make much sense and is actually forbidden in the new style (it will result in a ValueError).

Old

'%04d' % (42,)

New

'{:04d}'.format(42)

Output

0042

Signed numbers

By default only negative numbers are prefixed with a sign. This can be changed of course.

Old

'%+d' % (42,)

New

'{:+d}'.format(42)

Output

+42

Use a space character to indicate that negative numbers should be prefixed with a minus symbol and a leading space should be used for positive ones.

Old

'% d' % ((- 23),)

New

'{: d}'.format((- 23))

Output

-23

Old

'% d' % (42,)

New

'{: d}'.format(42)

Output

 42

New style formatting is also able to control the position of the sign symbol relative to the padding.

This operation is not available with old-style formatting.

New

'{:=5d}'.format((- 23))

Output

-  23

New

'{:=+5d}'.format(23)

Output

+  23

Named placeholders

Both formatting styles support named placeholders.

Setup

data = {'first': 'Hodor', 'last': 'Hodor!'}

Old

'%(first)s %(last)s' % data

New

'{first} {last}'.format(**data)

Output

Hodor Hodor!

.format() also accepts keyword arguments.

This operation is not available with old-style formatting.

New

'{first} {last}'.format(first='Hodor', last='Hodor!')

Output

Hodor Hodor!

Getitem and Getattr

New style formatting allows even greater flexibility in accessing nested data structures.

It supports accessing containers that support __getitem__ like for example dictionaries and lists:

This operation is not available with old-style formatting.

Setup

person = {'first': 'Jean-Luc', 'last': 'Picard'}

New

'{p[first]} {p[last]}'.format(p=person)

Output

Jean-Luc Picard

Setup

data = [4, 8, 15, 16, 23, 42]

New

'{d[4]} {d[5]}'.format(d=data)

Output

23 42

As well as accessing attributes on objects via getattr():

This operation is not available with old-style formatting.

Setup

class Plant(object):
type = 'tree'

New

'{p.type}'.format(p=Plant())

Output

tree

Both type of access can be freely mixed and arbitrarily nested:

This operation is not available with old-style formatting.

Setup

class Plant(object):
type = 'tree'
kinds = [{'name': 'oak'}, {'name': 'maple'}]

New

'{p.type}: {p.kinds[0][name]}'.format(p=Plant())

Output

tree: oak

Datetime

New style formatting also allows objects to control their own rendering. This for example allows datetime objects to be formatted inline:

This operation is not available with old-style formatting.

Setup

from datetime import datetime

New

'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5))

Output

2001-02-03 04:05

Parametrized formats

Additionally, new style formatting allows all of the components of the format to be specified dynamically using parametrization. Parametrized formats are nested expressions in braces that can appear anywhere in the parent format after the colon.

Old style formatting also supports some parametrization but is much more limited. Namely it only allows parametrization of the width and precision of the output.

Parametrized alignment and width:

This operation is not available with old-style formatting.

New

'{:{align}{width}}'.format('test', align='^', width='10')

Output

   test   

Parametrized precision:

Old

'%.*s = %.*f' % (3, 'Gibberish', 3, 2.7182)

New

'{:.{prec}} = {:.{prec}f}'.format('Gibberish', 2.7182, prec=3)

Output

Gib = 2.718

Width and precision:

Old

'%*.*f' % (5, 2, 2.7182)

New

'{:{width}.{prec}f}'.format(2.7182, width=5, prec=2)

Output

 2.72

The nested format can be used to replace any part of the format spec, so the precision example above could be rewritten as:

This operation is not available with old-style formatting.

New

'{:{prec}} = {:{prec}}'.format('Gibberish', 2.7182, prec='.3')

Output

Gib = 2.72

The components of a date-time can be set separately:

This operation is not available with old-style formatting.

Setup

from datetime import datetime
dt = datetime(2001, 2, 3, 4, 5)

New

'{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M')

Output

2001-02-03 04:05

The nested formats can be positional arguments. Position depends on the order of the opening curly braces:

This operation is not available with old-style formatting.

New

'{:{}{}{}.{}}'.format(2.7182818284, '>', '+', 10, 3)

Output

     +2.72

And of course keyword arguments can be added to the mix as before:

This operation is not available with old-style formatting.

New

'{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')

Output

     +2.72

Custom objects

The datetime example works through the use of the __format__() magic method. You can define custom format handling in your own objects by overriding this method. This gives you complete control over the format syntax used.

This operation is not available with old-style formatting.

Setup

class HAL9000(object):

    def __format__(self, format):
if (format == 'open-the-pod-bay-doors'):
return "I'm afraid I can't do that."
return 'HAL 9000'

New

'{:open-the-pod-bay-doors}'.format(HAL9000())

Output

I'm afraid I can't do that.

You might also like Python strftime reference by Will McCutchen.

Curated by Ulrich Petri & Horst Gutmann
Version: a1c121275553bb110befddb63ec540f9339acbf9 (built at 2017-04-30 18:51:04.145458+00:00)

# 下面是练习

"""

print ('{:3}'.format('test'))
print ('{:10}'.format('test'))
print ('{:*^10}'.format('test'))
print ('{:*>7}'.format('test'))
print ('{:*<7}'.format('test'))
'''
test
test
***test***
***test
test***
'''
print ('{:.5}'.format('test'))
print ('{:.5}'.format('abcdefg'))
print ('{:6.5}'.format('abcdefg'))
print ('{:10.5}'.format('abcdefg'))
'''
test
abcde
abcde
abcde
'''
print ('{:d}'.format(42))
print ('{:f}'.format(3.1415926))
print ('{:4d}'.format(42))
print ('{:04d}'.format(42))
#print ('{:00^4d}'.format(42)) #ValueError: Invalid format specifier
print ('{:0^4d}'.format(42))
'''
42
3.141593
42
0042
0420
'''
print ('{:06.2f}'.format(3.1415926)) #003.14
#print ('{: d}'.format(42)) #ValueError: Invalid format specifier
print ('{:+d}'.format(42))
print ('{: d}'.format(42))
print ('{: d}'.format( 42))
print ('{: d}'.format(-42))
print ('{: d}'.format(- 42))
print ('{: d}'.format(- 42))
'''
+42
42
42
-42
-42
-42
''' print ('{:5d}'.format(42))
print ('{:05d}'.format(42))
print ('{:=05d}'.format(42))
print ('{:=5d}'.format(42))
print ('{:=+5d}'.format(42))
print ('{:=5d}'.format(-42))
print ('{:=5d}'.format(- 42))
'''
42
00042
00042
42
+ 42
- 42
- 42
''' data = {'first': 'Hodor', 'last': 'Hodor!'}
print ('{first} {last}'.format(**data))
print ('{first} {last}'.format(first='Hodor', last='Hodor!'))
#print ('{data[first]} {data[last]}'.format(data)) #KeyError: 'data'
print ('{data[first]} {data[last]}'.format(data=data))
print ('{p[first]} {p[last]}'.format(p=data))
'''
Hodor Hodor!
Hodor Hodor!
Hodor Hodor!
Hodor Hodor!
''' data = [4, 8, 15, 16, 23, 42]
#print ('{data[4]} {data[5]}'.format(data)) #KeyError: 'data'
#print ('{data[4]} {data[5]}'.format(*data)) #KeyError: 'data'
#print ('{[4]} {[5]}'.format(*data)) #TypeError: 'int' object is not subscriptable
print ('{4} {5}'.format(*data))
print ('{p[4]} {p[5]}'.format(p=data))
'''
23 42
23 42
''' class Plant(object):
type = 'tree' print ('{p.type}'.format(p=Plant())) #tree class Plant(object):
type = 'tree'
kinds = [{'name': 'oak'}, {'name': 'maple'}] print ('{p.type}:{p.kinds[0][name]}'.format(p=Plant())) #tree:oak from datetime import datetime print ('{:%Y-%m-%d %H:%M}'.format(datetime(2020, 4, 13, 15, 15))) #2020-04-13 15:15 print ('{:{align}{width}}'.format('test', align='^', width=10))
'''
test
''' print ('{:.{prec}} = {:.{prec}f}'.format('Gibbrish', 3.1415926, prec=3)) #Gib = 3.142
print ('{:{width}.{prec}f}'.format(3.1415926, width=10, prec=2))
print ('{:{width}.{prec}}'.format(3.1415926, width=10, prec=2))
print ('{:*^{width}.{prec}f}'.format(3.1415926, width=10, prec=2))
print ('{:*>{width}.{prec}f}'.format(3.1415926, width=10, prec=2))
print ('{:{prec}} = {:{prec}}'.format('Gibberish', 3.1415926, prec='.3'))
'''
3.14
3.1
***3.14***
******3.14
Gib = 3.14
''' from datetime import datetime
dt = datetime(2020, 4, 13, 15, 36) print ('{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M')) #2020-04-13 15:36 print ('{:*>+10}'.format(2.344)) #****+2.344
print ('{:{}{}{}{}.{}}'.format(3.141, '*', '>', '+', 10, 2)) #******+3.1
print ('{:{}{}{asign}{}.{}}'.format(3.1415, '*', '>', 10, 2, asign='+')) #******+3.1 """
class HAL9000(object): def __format__(self, format_spec):
if format_spec == 'open-the-door':
return "I'm afrait i can not do that"
return 'HAL 9000' print ('{:open-the-door}'.format(HAL9000())) #I'm afrait i can not do that

【Python】【fmt】的更多相关文章

  1. 【python 字典、json】python字典和Json的相互转换

    [python 字典.json]python字典和Json的相互转换 dump/dumps字典转换成json load/loadsjson转化成字典 dumps.loads直接输出字符 dump.lo ...

  2. 【Python成长之路】Python爬虫 --requests库爬取网站乱码(\xe4\xb8\xb0\xe5\xa)的解决方法【华为云分享】

    [写在前面] 在用requests库对自己的CSDN个人博客(https://blog.csdn.net/yuzipeng)进行爬取时,发现乱码报错(\xe4\xb8\xb0\xe5\xaf\x8c\ ...

  3. 【Python成长之路】装逼的一行代码:快速共享文件

    [Python成长之路]装逼的一行代码:快速共享文件 2019-10-26 15:30:05 华为云 阅读数 335 文章标签: Python编程编程语言程序员Python开发 更多 分类专栏: 技术 ...

  4. 【Python成长之路】词云图制作

    [写在前面] 以前看到过一些大神制作的词云图 ,觉得效果很有意思.如果有朋友不了解词云图的效果,可以看下面的几张图(图片都是网上找到的): 网上找了找相关的软件,有些软件制作 还要付费.结果前几天在大 ...

  5. 【Python成长之路】装逼的一行代码:快速共享文件【华为云分享】

    [写在前面] 有时候会与同事共享文件,正常人的操作是鼠标右键,点击共享.其实有个装逼的方法,用python的一行代码快速实现基于http服务的共享方式. [效果如下] [示例代码] 在cmd窗口进入想 ...

  6. 【Python成长之路】从 零做网站开发 -- 基于Flask和JQuery,实现表格管理平台

    [写在前面] 你要开发网站?    嗯.. 会Flask吗?    什么东西,没听过... 会JQuery吗?    是python的库吗 ? 那你会什么?    我会F12打开网站 好吧,那我们来写 ...

  7. 朴素贝叶斯算法源码分析及代码实战【python sklearn/spark ML】

    一.简介 贝叶斯定理是关于随机事件A和事件B的条件概率的一个定理.通常在事件A发生的前提下事件B发生的概率,与在事件B发生的前提下事件A发生的概率是不一致的.然而,这两者之间有确定的关系,贝叶斯定理就 ...

  8. 【Python—字典的用法】创建字典的3种方法

    #创建一个空字典 empty_dict = dict() print(empty_dict) #用**kwargs可变参数传入关键字创建字典 a = dict(one=1,two=2,three=3) ...

  9. 【python之路42】web框架们的具体用法

    Python的WEB框架 (一).Bottle Bottle是一个快速.简洁.轻量级的基于WSIG的微型Web框架,此框架只由一个 .py 文件,除了Python的标准库外,其不依赖任何其他模块. p ...

  10. 【python之路35】网络编程之socket相关

    Socket socket通常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄,应用程序通常通过"套接字"向网络发出请求或者应答网络请求. sock ...

随机推荐

  1. zabbix3.0 centos7 yum 安装与简单配置

    参考文档https://www.zabbix.com/documentation/3.0/start zabbix是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案.zab ...

  2. iOS开发--图片轮播

    直接上代码了,比较简单.演示下载地址:Demo // // UYViewController.m // 图片轮播器 // // Created by jiangys on 15/5/23. // Co ...

  3. Perl的debug小技巧

    进入Perl的调试环境的命令:  Perl  -d  perl_file 设置断点:b + perl代码中的行号. 执行到断点:c 表示continue until breakpoint. 执行下一条 ...

  4. 172. Factorial Trailing Zeroes(阶乘中0的个数 数学题)

    Given an integer n, return the number of trailing zeroes in n!. Example 1: Input: 3 Output: 0 Explan ...

  5. font-awesome图标

  6. 20155222 2016-2017-2 《Java程序设计》第8周学习总结

    20155222 2016-2017-2 <Java程序设计>第8周学习总结 教材学习内容总结 Java NIO(New IO)是一个可以替代标准Java IO API的IO API(从J ...

  7. 怎么归档老日志的shell脚本

    本脚本来自有学习阿铭的博文学习:工作中,需要用到日志切割logrotate,按照各自的需要切割.定义保留日志.提示:本文中的S全部都$符,不要问为什么,马云爸爸的社区就这样. #用途:日志切割归档.按 ...

  8. 4 个技巧学习 Golang

    到达 Golang 大陆:一位资深开发者之旅. 2014 年夏天…… IBM:“我们需要你弄清楚这个 Docker.” 我:“没问题.” IBM:“那就开始吧.” 我:“好的.”(内心声音):”Doc ...

  9. 如何写出一个让人很难发现的bug?

    程序员的日常三件事:写bug.改bug.背锅.连程序员都自我调侃道,为什么每天都在加班?因为我的眼里常含bug. 那么如何写出一个让(坑)人(王)很(之)难(王)发现的bug呢? - 1 -新手开发+ ...

  10. stm32 学习参考(转)

    源:stm32 学习参考 单片机裸机下写一个自己的shell调试器     LWIP_STM32_ENC28J60_NETCONN_TCP_SERVICER(5)     LWIP_STM32_ENC ...