Python format 格式化字符串
260 views
0
Python中格式化输出字符串使用format()函数, 字符串即类, 可以使用方法;
Python是完全面向对象的语言, 任何东西都是对象;
字符串的参数使用{NUM}进行表示,0, 表示第一个参数,1, 表示第二个参数, 以后顺次递加;
使用:, 指定代表元素需要的操作, 如:.3小数点三位, :8占8个字符空间等;
数字(0, 1, ...)即代表format()里面的元素, 所以可以使用.调用元素的方法;
代码如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ithomer.net
# 2014-09-06
# python2.7 python3.3
host = 'ithomer.net'
blog = 'blog.ithomer.net'
forum = 'forum.ithomer.net'
year = 2014
print('{0} is {1} years old. '.format(host, year)) # 输出参数, 0 - 指定第一个
print('{} is {} years old. '.format(host, year)) # 默认
print('{0} is a blog. '.format(blog))
print('{0:.3} is a decimal. '.format(1.0/3)) # 小数点后三位
print('{0:.3} is a decimal. '.format(10.0/3)) # 小数点后三位
print('{0:_^11} is a 11 length. '.format(year)) # 使用_补齐空位
print('{first} is as {second}. '.format(first = host, second = 'Sunday')) # 别名替换
print('My name is {0.name}'.format(open('out.txt', 'w'))) # 调用方法
print('My name is {0:8}.'.format('Fred')) # 指定宽度
# 运行结果:
# ithomer.net is 2014 years old.
# ithomer.net is 2014 years old.
# blog.ithomer.net is a blog.
# 0.333 is a decimal.
# 3.33 is a decimal.
# ___2014____ is a 11 length.
# ithomer.net is as Sunday.
# My name is out.txt
# My name is Fred .
参考推荐:
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2020-12-11 16:10:22
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!