Programming

Python의 기능과 같은 sprintf

procodes 2020. 7. 28. 22:03
반응형

Python의 기능과 같은 sprintf


sprintf파이썬에서 C 스타일 기능을 사용하여 텍스트 파일에 버퍼를 작성하고 처리하고 많은 처리를 수행하는 문자열 버퍼를 만들고 싶습니다 . 조건문 때문에 파일에 직접 쓸 수 없습니다.

예 : 의사 코드 :

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

따라서 출력 파일에는 다음과 같은 종류의 o / p가 있습니다.

A= foo B= bar
C= ded
etc...

내 질문을 명확히하기 위해 편집 :
buf 큰 버퍼는 sprintf를 사용하여 형식이 지정된 모든 문자열을 포함합니다. 예를 들어, buf이전 값이 아닌 현재 값만 포함합니다. 예를 들어 나중에 buf첫 번째 내용 은 동일하게 추가 되었지만 Python 답변 에는 마지막 값만 포함되어 있습니다. 필자는 아닙니다 . 처음부터와 같이 시작한 모든 것을 갖고 싶습니다 .A= something ,B= somethingC= somethingbufbufbufprintfC


파이썬에는이를위한 %연산자가 있습니다.

>>> 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

지원되는 모든 형식 지정자에 대해서는이 참조참조하십시오 .

당신은뿐만 아니라 사용할 수 있습니다 format:

>>> print "This is the {}th tome of {}".format(5, "knowledge")
This is the 5th tome of knowledge

귀하의 질문을 올바르게 이해하면 format ()mini-language 와 함께 찾고 있습니다 .

파이썬 2.7 이상의 어리석은 예 :

>>> print "{} ...\r\n {}!".format("Hello", "world")
Hello ...
 world!

이전 파이썬 버전의 경우 : (2.6.2로 테스트)

>>> print "{0} ...\r\n {1}!".format("Hello", "world")
Hello ...
 world!

목표를 이해한다고 확신 할 수는 없지만 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

와 달리 sprintf문자열을에 전달 buf.write하여 %연산자 나 format문자열 메서드로 형식을 지정합니다 .

물론 원하는 sprintf인터페이스 를 얻는 함수를 정의 할 수 있습니다.

def sprintf(buf, fmt, *args):
    buf.write(fmt % args)

다음과 같이 사용됩니다.

>>> 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

형식화 연산자를% 사용하십시오 .

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

문자열 형식을 사용할 수 있습니다.

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

그러나 이것은 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'

매우 긴 문자열에 삽입하려면 올바른 위치에 있기를 바라지 않고 다른 인수에 이름을 사용하는 것이 좋습니다. 또한 여러 반복을 쉽게 교체 할 수 있습니다.

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'

Taken from Format examples, where all the other Format-related answers are also shown.


This is probably the closest translation from your C code to Python code.

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()

The % operator in Python does almost exactly the same thing as C's sprintf. You can also print the string to a file directly. If there are lots of these string formatted stringlets involved, it might be wise to use a StringIO object to speed up processing time.

So instead of doing +=, do this:

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()

Take a look at "Literal String Interpolation" https://www.python.org/dev/peps/pep-0498/

I found it through the http://www.malemburg.com/


Something like...

name = "John"

print("Hello %s", name)

Hello John

If you want something like the python3 print function but to a string:

def sprint(*args, **kwargs):
    sio = io.StringIO()
    print(*args, **kwargs, file=sio)
    return sio.getvalue()
>>> 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"

or without the '\n' at the end:

def sprint(*args, end='', **kwargs):
    sio = io.StringIO()
    print(*args, **kwargs, end=end, file=sio)
    return sio.getvalue()
>>> 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}"

참고URL : https://stackoverflow.com/questions/5309978/sprintf-like-functionality-in-python

반응형