Programming

Python에서 문자열 형식화에 여러 인수 사용 (예 : '% s… % s')

procodes 2020. 6. 5. 22:02
반응형

Python에서 문자열 형식화에 여러 인수 사용 (예 : '% s… % s')


모양이 문자열이며 '%s in %s'인수를 분리하여 두 가지 % s가되도록 인수를 분리하는 방법을 알고 싶습니다. Java에서 오는 내 마음은 이것을 생각해 냈습니다.

'%s in %s' % unicode(self.author),  unicode(self.publication)

그러나 이것은 작동하지 않으므로 파이썬에서는 어떻게 보입니까?


Mark Cidade의 답변이 옳습니다-튜플을 제공해야합니다.

그러나 Python 2.6부터는 다음 format대신 사용할 수 있습니다 %.

'{0} in {1}'.format(unicode(self.author,'utf-8'),  unicode(self.publication,'utf-8'))

%더 이상 문자열 형식화를 사용 하지 않는 것이 좋습니다.

이 문자열 형식화 방법은 Python 3.0의 새로운 표준이며 새 코드의 문자열 형식화 작업에 설명 된 % 형식화보다 선호됩니다.


둘 이상의 인수를 사용하는 경우 튜플에 있어야합니다 (추가 괄호 참조).

'%s in %s' % (unicode(self.author),  unicode(self.publication))

EOL에서 지적했듯이이 unicode()함수는 일반적으로 ASCII 인코딩을 기본값으로 가정하므로 ASCII가 아닌 문자가 있으면 인코딩을 명시 적으로 전달하는 것이 더 안전합니다.

'%s in %s' % (unicode(self.author,'utf-8'),  unicode(self.publication('utf-8')))

Python 3.0부터는 str.format()구문을 대신 사용하는 것이 좋습니다.

'{0} in {1}'.format(unicode(self.author,'utf-8'),unicode(self.publication,'utf-8'))

다중 인수에 대한 튜플 / 매핑 객체 format

다음은 설명서에서 발췌 한 것입니다.

을 감안할 때 format % values, %변환 사양에서 format0 개 이상의 요소로 대체됩니다 values. 이 효과는 sprintf()C 언어에서의 사용과 유사합니다 .

format단일 인수가 필요한 경우 값은 단일 비 튜플 객체 일 수 있습니다. 그렇지 않으면, 값은에 의해 지정된 항목을 정확히 번호 튜플해야 format문자열 , 또는 단일 매핑 객체 (예를 들어, 사전).

참고 문헌


str.format대신%

%연산자 의 새로운 대안 은을 사용하는 것 str.format입니다. 다음은 설명서에서 발췌 한 내용입니다.

str.format(*args, **kwargs)

문자열 형식화 작업을 수행하십시오. 이 메소드가 호출되는 문자열은 중괄호로 구분 된 리터럴 텍스트 또는 대체 필드를 포함 할 수 있습니다 {}. 각 대체 필드에는 위치 인수의 숫자 색인 또는 키워드 인수의 이름이 있습니다. 각 교체 필드가 ​​해당 인수의 문자열 값으로 대체되는 문자열의 복사본을 반환합니다.

이 메소드는 Python 3.0의 새로운 표준이며 %형식화 보다 선호됩니다 .

참고 문헌


사용 예는 다음과 같습니다.

>>> '%s for %s' % ("tit", "tat")
tit for tat

>>> '{} and {}'.format("chicken", "waffles")
chicken and waffles

>>> '%(last)s, %(first)s %(last)s' % {'first': "James", 'last': "Bond"}
Bond, James Bond

>>> '{last}, {first} {last}'.format(first="James", last="Bond")
Bond, James Bond

또한보십시오


값을 괄호 안에 넣어야합니다.

'%s in %s' % (unicode(self.author),  unicode(self.publication))

여기서, 제에 대한 배치됩니다. 그리고 초 동안 의이 사용됩니다.%sunicode(self.author)%sunicode(self.publication)

참고 : 표기법 string formatting보다 선호해야합니다 %. 더 많은 정보는 여기에


지금까지 게시 된 답변 중 일부에 중대한 문제가 unicode()있습니다. 기본 인코딩 (일반적으로 ASCII 임)에서 디코딩합니다. 실제로, unicode()바이트를 문자로 변환하여 주어진 바이트를 "감지"시키려고합니다. 따라서 이전 답변에서 권장하는 다음 코드는 내 컴퓨터에서 실패합니다.

# -*- coding: utf-8 -*-
author = 'éric'
print '{0}'.format(unicode(author))

제공합니다 :

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    print '{0}'.format(unicode(author))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

오류는 authorASCII 바이트 만 포함하지 않고 (예 : [0; 127] 값) unicode()기본적으로 (많은 컴퓨터에서) ASCII에서 디코딩 한다는 사실에서 발생 합니다 .

A robust solution is to explicitly give the encoding used in your fields; taking UTF-8 as an example:

u'{0} in {1}'.format(unicode(self.author, 'utf-8'), unicode(self.publication, 'utf-8'))

(or without the initial u, depending on whether you want a Unicode result or a byte string).

At this point, one might want to consider having the author and publication fields be Unicode strings, instead of decoding them during formatting.


For python2 you can also do this

'%(author)s in %(publication)s'%{'author':unicode(self.author),
                                  'publication':unicode(self.publication)}

which is handy if you have a lot of arguments to substitute (particularly if you are doing internationalisation)

Python2.6 onwards supports .format()

'{author} in {publication}'.format(author=self.author,
                                   publication=self.publication)

You could also use it clean and simple (but wrong! because you should use format like Mark Byers said) by doing:

print 'This is my %s formatted with %d arguments' % ('string', 2)

For completeness, in python 3.6 f-string are introduced in PEP-498. These strings make it possible to

embed expressions inside string literals, using a minimal syntax.

That would mean that for your example you could also use:

f'{self.author} in {self.publication}'

참고URL : https://stackoverflow.com/questions/3395138/using-multiple-arguments-for-string-formatting-in-python-e-g-s-s

반응형