sprintf就像Python中的功能一样

spr*_*ing 117 python string

我想创建一个字符串缓冲区来进行大量处理,格式化,最后使用sprintfPython中的C风格功能将缓冲区写入文本文件中.由于条件语句,我不能直接将它们写入文件.

例如伪代码:

sprintf(buf,"A = %d\n , B= %s\n",A,B)
/* some processing */
sprint(buf,"C=%d\n",c)
....
...
fprintf(file,buf)
Run Code Online (Sandbox Code Playgroud)

所以在输出文件中我们有这种o/p:

A= foo B= bar
C= ded
etc...
Run Code Online (Sandbox Code Playgroud)

编辑,澄清我的问题:
buf是一个大缓冲区包含所有这些使用sprintf格式化的字符串.按照您的示例,buf只包含当前值,而不是旧值.例如,buf我在A= something ,B= something后面写的第一个C= something附加在同一个buf,但在你的Python答案buf中只包含最后一个值,这不是我想要的 - 我想buf拥有printf我从一开始就做的所有s,就像在C.

Ale*_*lik 155

Python有一个%运算符.

>>> a = 5
>>> b = "hello"
>>> buf = "A = %d\n , B = %s\n" % (a, b)
>>> print buf
A = 5
 , B = hello

>>> c = 10
>>> buf = "C = %d\n" % c
>>> print buf
C = 10
Run Code Online (Sandbox Code Playgroud)

有关所有支持的格式说明符,请参阅此参考.

你也可以使用format:

>>> print "This is the {}th tome of {}".format(5, "knowledge")
This is the 5th tome of knowledge
Run Code Online (Sandbox Code Playgroud)


Nic*_*vre 39

如果我理解你的问题,格式()就是你正在寻找的,以及它的迷你语言.

python 2.7及以上的愚蠢示例:

>>> print "{} ...\r\n {}!".format("Hello", "world")
Hello ...
 world!
Run Code Online (Sandbox Code Playgroud)

对于早期的python版本:(使用2.6.2测试)

>>> print "{0} ...\r\n {1}!".format("Hello", "world")
Hello ...
 world!
Run Code Online (Sandbox Code Playgroud)

  • 您应该注意到该版本仅适用于Python 3.例如,在Python 2.6中,您需要执行以下操作:`"{0} ...\r \n {1}!".format("Hello","世界")` (4认同)

Mic*_*ber 17

我不完全确定我理解你的目标,但你可以使用一个StringIO实例作为缓冲区:

>>> import StringIO 
>>> buf = StringIO.StringIO()
>>> buf.write("A = %d, B = %s\n" % (3, "bar"))
>>> buf.write("C=%d\n" % 5)
>>> print(buf.getvalue())
A = 3, B = bar
C=5
Run Code Online (Sandbox Code Playgroud)

与之不同sprintf,您只需将字符串传递给buf.write,使用%运算符或format字符串方法对其进行格式化.

您当然可以定义一个函数来获取sprintf您希望的接口:

def sprintf(buf, fmt, *args):
    buf.write(fmt % args)
Run Code Online (Sandbox Code Playgroud)

将使用这样:

>>> buf = StringIO.StringIO()
>>> sprintf(buf, "A = %d, B = %s\n", 3, "foo")
>>> sprintf(buf, "C = %d\n", 5)
>>> print(buf.getvalue())
A = 3, B = foo
C = 5
Run Code Online (Sandbox Code Playgroud)

  • 对于 Python3,请使用 `io.StringIO()` 代替 (3认同)
  • +1用于向我展示如何使用*args和字符串格式化运算符(%). (2认同)

NPE*_*NPE 13

使用格式化运算符%:

buf = "A = %d\n , B= %s\n" % (a, b)
print >>f, buf
Run Code Online (Sandbox Code Playgroud)


utd*_*mir 10

您可以使用字符串格式:

>>> a=42
>>> b="bar"
>>> "The number is %d and the word is %s" % (a,b)
'The number is 42 and the word is bar'
Run Code Online (Sandbox Code Playgroud)

但是在Python 3中删除了这个,你应该使用"str.format()":

>>> a=42
>>> b="bar"
>>> "The number is {0} and the word is {1}".format(a,b)
'The number is 42 and the word is bar'
Run Code Online (Sandbox Code Playgroud)

  • 错误,它不会在Python 3中删除.Python 3.0表示它将在3.1中弃用但我相信从未发生过.使用`format()`可能更好,但`%`格式仍然存在.(请参阅http://mail.python.org/pipermail/python-dev/2009-September/092399.html,了解其未被弃用的原因) (4认同)

Jos*_*ost 7

要插入一个非常长的字符串,最好使用不同参数的名称,而不是希望它们处于正确的位置.这也可以更容易地替换多次重复.

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
Run Code Online (Sandbox Code Playgroud)

取自格式示例,其中Format还显示了所有其他相关答案.


Mic*_*ael 7

如果你想要像 python3 打印函数但字符串:

def sprint(*args, **kwargs):
    sio = io.StringIO()
    print(*args, **kwargs, file=sio)
    return sio.getvalue()
Run Code Online (Sandbox Code Playgroud)
>>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
>>> x
"abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}\n"
Run Code Online (Sandbox Code Playgroud)

或者没有'\n'结尾:

def sprint(*args, end='', **kwargs):
    sio = io.StringIO()
    print(*args, **kwargs, end=end, file=sio)
    return sio.getvalue()
Run Code Online (Sandbox Code Playgroud)
>>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
>>> x
"abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}"
Run Code Online (Sandbox Code Playgroud)

  • 不知道为什么其他所有答案都在回避实际问题。谢谢你。 (2认同)

Y.H*_*ong 5

这可能是从 C 代码到 Python 代码最接近的翻译。

A = 1
B = "hello"
buf = "A = %d\n , B= %s\n" % (A, B)

c = 2
buf += "C=%d\n" % c

f = open('output.txt', 'w')
print >> f, c
f.close()
Run Code Online (Sandbox Code Playgroud)

Python 中的运算%符与 C 中的运算符几乎执行相同的操作sprintf。您还可以直接将字符串打印到文件中。如果涉及大量此类字符串格式的 stringlet,那么使用StringIO对象来加快处理时间可能是明智之举。

因此,不要这样做+=,而是这样做:

import cStringIO
buf = cStringIO.StringIO()

...

print >> buf, "A = %d\n , B= %s\n" % (A, B)

...

print >> buf, "C=%d\n" % c

...

print >> f, buf.getvalue()
Run Code Online (Sandbox Code Playgroud)


Mar*_*ark 5

我知道这是一个旧线程 - 但有一个新的字符串插值“样式” - f'' 字符串格式化构造。

a = 5
b = "hello"
buf = f"A = {a:d}\n , B = {b}\n" 
Run Code Online (Sandbox Code Playgroud)

F-String(如其名称)在PEP-498中指定。

在学习 F-String 之前,我会调用如下格式:

a = 5
b = "hello"
buf = "A = {a:d}\n , B = {b}\n".format( **{ **globals() , **locals() } ) 
Run Code Online (Sandbox Code Playgroud)

根据 PEP-498 文档,F-String 在 Python 3.6 或更高版本中可用。