IT Share you

파이썬에서 % r의 의미는 무엇입니까

shareyou 2020. 11. 27. 21:43
반응형

파이썬에서 % r의 의미는 무엇입니까


%r다음 문장에서 의 의미는 무엇 입니까?

print '%r' % (1)

내가 들어 본 것 같은데 %s, %d하고 %f있지만 들어 본 적이.


배경:

: 파이썬에서, 문자열로 객체를 돌려 두 가지 내장 기능이 있습니다 str대는 repr. str친숙하고 사람이 읽을 수있는 문자열이어야합니다. repr객체의 내용에 대한 자세한 정보를 포함해야합니다 (때로는 정수와 같은 동일한 것을 반환합니다). 관례 적으로 == 인 다른 객체로 평가할 파이썬 표현식이 있다면, 다음 repr과 같은 표현식을 반환합니다.

>>> print repr ( 'hi')
'hi'# 여기에 따옴표가 있습니다.
>>> print str ( 'hi')
안녕하세요

표현식을 반환하는 것이 객체에 적합하지 않은 경우 repr<및> 기호로 둘러싸인 문자열을 반환해야합니다 (예 : <blah>.

원래 질문에 답하려면 :

%s<-> <->str
%rrepr

게다가:

__str____repr__메서드 를 구현하여 자체 클래스의 인스턴스가 문자열로 변환되는 방식을 제어 할 수 있습니다 .

class Foo:

  def __init__(self, foo):
    self.foo = foo

  def __eq__(self, other):
    """Implements ==."""
    return self.foo == other.foo

  def __repr__(self):
    # if you eval the return value of this function,
    # you'll get another Foo instance that's == to self
    return "Foo(%r)" % self.foo

repr()객체를 호출 하고 결과 문자열을 삽입합니다.


교체를 repr().


위에 제공된 응답에 추가하면 '%r'이기종 데이터 유형의 목록이있는 시나리오에서 유용 할 수 있습니다. 하자의 말, 우리는이 list = [1, 'apple' , 2 , 'r','banana']사용이 경우에는 분명히 '%d'또는 '%s'오류가 발생합니다. 대신 '%r'이 모든 값을 인쇄 하는 사용할 수 있습니다 .


%r%sis 의 차이점 %rrepr()메서드를 %s호출하고 str()메서드를 호출하는 것입니다. 둘 다 내장 Python 함수입니다.

repr()메서드는 지정된 개체의 인쇄 가능한 표현을 반환합니다. str()메서드는 주어진 객체의 "비공식적"또는 멋지게 인쇄 가능한 표현을 반환합니다.

간단한 언어로 str()메서드가하는 일은 최종 사용자가보고 싶어하는 방식으로 결과를 인쇄하는 것입니다.

name = "Adam"
str(name)
Out[1]: 'Adam'

repr()메서드는 개체가 실제로 어떻게 보이는지 인쇄하거나 표시합니다.

name = "Adam"
repr(name)
Out[1]: "'Adam'"

%s__str()__선택한 개체 메서드를 호출하고 자체를 반환 값으로 바꿉니다.

%r__repr()__선택한 개체 메서드를 호출하고 자체를 반환 값으로 바꿉니다.


%s <=> str
%r <=> repr

%r calls repr() on the object, and inserts the resulting string returned by __repr__.

The string returned by __repr__ should be unambiguous and, if possible, match the source code necessary to recreate the object being represented.

A quick example:

class Foo:

    def __init__(self, foo):
        self.foo = foo


    def __repr__(self):
        return 'Foo(%r)' % self.foo

    def __str__(self):
        return self.foo


test = Foo('Text')

So,

in[1]: test
Out[1]: Foo('Text')


in[2]: str(test)
Out[2]: 'Text'

See String Formatting Operations in the docs. Notice that %s and %d etc, might work differently to how you expect if you are used to the way they work in another language such as C.

In particular, %s also works well for ints and floats unless you have special formatting requirements where %d or %f will give you more control.

참고URL : https://stackoverflow.com/questions/2354329/whats-the-meaning-of-r-in-python

반응형