PyFormat

字符串格式化实例
授权协议 MIT
开发语言 Python
所属分类 开发工具、 Python开发工具
软件类型 开源软件
地区 不详
投 递 者 燕元明
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

PyFormat 是记录 Python 字符串格式化系统的实例的项目。python.org 的官方文档中,包含了大量的关于格式化语法规范的信息,以及一些例子,但他们的文档太理论和技术化了。这个项目把常用格式化的新老风格直观地展示出来,提供了实际的例子。

如果没有特别注明外,所有的例子使用 Python2.7,3.2,3.3,和3.4,而无需任何额外的库或 monkey-patching。

基本的格式化:

Old

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

New

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

Output

one two

数值转换:

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


填充和对齐字符串:

右对齐:

Old

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

New

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

Output

      test


长字符串截位:

Old

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

New

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

Output

xylop
  • %s 是从 C语言借来的 string formatting syntax; #Python2 name = raw_input("who are you? ") print "hello %s" % (name,) #Python3+ name = input("who are you? ") print("hello %s" % (name,)) The %s token allows me

 相关资料
  • 主要内容:指定最小输出宽度,指定对齐方式,指定小数精度我们在《 第一个Python程序——在屏幕上输出文本》中讲到过 print() 函数的用法,这只是最简单最初级的形式,print() 还有很多高级的玩法,比如格式化输出,这就是本节要讲解的内容。 熟悉C语言 printf() 函数的读者能够轻而易举学会 Python print() 函数,它们是非常类似的。 print() 函数使用以 开头的转换说明符对各种类型的数据进行格式化输出,具体请看下表。

  • Parameter Position参数位置 Type参数类型 Required必需 Default默认 Description描述 1 string Yes n/a This is what format to use. (sprintf) 使用的格式化方式 This is a way to format strings, such as decimal numbers and such. Us

  • Go对字符串格式化提供了良好的支持。下面我们看些常用的字符串格式化的例子。 package main import "fmt" import "os" type point struct { x, y int } func main() { // Go提供了几种打印格式,用来格式化一般的Go值,例如 // 下面的%v打印了一个point结构体的对象的值 p := p

  • 3.5. 格式化字符串 Python 支持格式化字符串的输出 。尽管这样可能会用到非常复杂的表达式, 但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中。 在 Python 中, 字符串格式化使用与 C 中 sprintf 函数一样的语法。 例 3.21. 字符串的格式化 >>> k = "uid" >>> v = "sa" >>> "%s=%s" % (k, v) 'uid=s

  • 由来 我一直对Slf4j的字符串格式化情有独钟,通过{}这种简单的占位符完成字符串的格式化。于是参考Slf4j的源码,便有了StrFormatter。 StrFormatter.format的快捷使用方式为StrUtil.format,推荐使用后者。 使用 //通常使用 String result1 = StrFormatter.format("this is {} for {}", "a", "

  • 问题内容: 我看到许多人使用这样的格式字符串: 而不是像这样简单地串联字符串: 格式字符串是否具有更好的性能,还是仅用于外观? 问题答案: 这只是为了外观。您可以一眼看出格式是什么。我们中的许多人都比微优化更喜欢可读性。 让我们看看IPython的意思:

  • Summary This section describes how to test for format string attacks that can be used to crash a program or to execute harmful code. The problem stems from the use of unfiltered user input as the form

  • rank ▲ ✰ vote url 70 354 145 282 url 字符串格式化:%和.format Python2.6推出了[str.format()]方法,和原有的%格式化方式有小小的区别.那个方法更好? 下面的方法有同样的输出,它们的区别是什么? #!/usr/bin/python sub1 = "python string!" sub2 = "an arg" a = "i