[python] python-3.x에서 사전을 사용하여 문자열을 어떻게 포맷합니까?

나는 사전을 사용하여 문자열을 포맷하는 것을 좋아합니다. 사용중인 문자열 형식을 읽고 기존 사전을 활용할 수 있습니다. 예를 들면 다음과 같습니다.

class MyClass:
    def __init__(self):
        self.title = 'Title'

a = MyClass()
print 'The title is %(title)s' % a.__dict__

path = '/path/to/a/file'
print 'You put your file here: %(path)s' % locals()

그러나 동일한 작업을 수행하거나 가능한 경우 Python 3.x 구문을 파악할 수 없습니다. 나는 다음을하고 싶다

# Fails, KeyError 'latitude'
geopoint = {'latitude':41.123,'longitude':71.091}
print '{latitude} {longitude}'.format(geopoint)

# Succeeds
print '{latitude} {longitude}'.format(latitude=41.123,longitude=71.091)



답변

이 질문은 Python 3에만 해당되므로 Python 3.6부터 사용할 수 있는 새로운 f-string 구문 을 사용 합니다 .

>>> geopoint = {'latitude':41.123,'longitude':71.091}
>>> print(f'{geopoint["latitude"]} {geopoint["longitude"]}')
41.123 71.091

외부 작은 따옴표와 내부 큰 따옴표를 참고하십시오 (다른 방법으로도 할 수 있습니다).


답변

이것이 당신에게 좋습니까?

geopoint = {'latitude':41.123,'longitude':71.091}
print('{latitude} {longitude}'.format(**geopoint))


답변

사전을 키워드 인수로 압축 해제하려면을 사용하십시오 **. 또한 새 스타일 형식은 객체의 속성 및 매핑 항목 참조를 지원합니다.

'{0[latitude]} {0[longitude]}'.format(geopoint)
'The title is {0.title}s'.format(a) # the a from your first example


답변

Python 3.0과 3.1은 EOL이며 아무도 사용하지 않기 때문에 (Python 3.2+)를 사용할 수 있고 사용해야합니다 str.format_map(mapping).

유사하게 str.format(**mapping), 그 매핑을 제외시켰다 직접 아닌 복사 사용된다dict . 예를 들어 매핑이 dict하위 클래스 인 경우에 유용합니다 .

이것이 의미 defaultdict하는 것은 누락 된 키의 기본값을 설정하고 반환 하는 것과 같은 것을 사용할 수 있다는 것입니다.

>>> from collections import defaultdict
>>> vals = defaultdict(lambda: '<unset>', {'bar': 'baz'})
>>> 'foo is {foo} and bar is {bar}'.format_map(vals)
'foo is <unset> and bar is baz'

제공된 맵핑 dict이 서브 클래스가 아닌 인 경우에도 여전히 약간 더 빠릅니다.

그래도 차이는 크지 않습니다.

>>> d = dict(foo='x', bar='y', baz='z')

그때

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format_map(d)

약 10ns (2 %)보다 빠름

>>> 'foo is {foo}, bar is {bar} and baz is {baz}'.format(**d)

내 파이썬에서 3.4.3. 사전에 더 많은 키가있을수록 차이가 더 커질 수 있습니다.


형식 언어는 그보다 훨씬 유연합니다. 인덱스 식, 속성 액세스 등을 포함 할 있으므로 전체 개체 또는 그 중 2 개의 형식을 지정할 있습니다.

>>> p1 = {'latitude':41.123,'longitude':71.091}
>>> p2 = {'latitude':56.456,'longitude':23.456}
>>> '{0[latitude]} {0[longitude]} - {1[latitude]} {1[longitude]}'.format(p1, p2)
'41.123 71.091 - 56.456 23.456'

3.6부터 보간 문자열도 사용할 수 있습니다.

>>> f'lat:{p1["latitude"]} lng:{p1["longitude"]}'
'lat:41.123 lng:71.091'

중첩 된 따옴표 안에 다른 따옴표 문자 를 사용해야 합니다. 이 방법의 또 다른 장점은 형식화 메서드를 호출하는 것보다 훨씬 빠릅니다 .


답변

print("{latitude} {longitude}".format(**geopoint))


답변

Python 2 구문은 Python 3에서도 작동합니다.

>>> class MyClass:
...     def __init__(self):
...         self.title = 'Title'
...
>>> a = MyClass()
>>> print('The title is %(title)s' % a.__dict__)
The title is Title
>>>
>>> path = '/path/to/a/file'
>>> print('You put your file here: %(path)s' % locals())
You put your file here: /path/to/a/file


답변

geopoint = {'latitude':41.123,'longitude':71.091}

# working examples.
print(f'{geopoint["latitude"]} {geopoint["longitude"]}') # from above answer
print('{geopoint[latitude]} {geopoint[longitude]}'.format(geopoint=geopoint)) # alternate for format method  (including dict name in string).
print('%(latitude)s %(longitude)s'%geopoint) # thanks @tcll