programing

python-3.x의 사전을 사용하여 문자열을 포맷하려면 어떻게 해야 합니까?

coolbiz 2022. 9. 28. 23:08
반응형

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)

이게 당신에게 좋습니까?

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'sed이고 아무도 사용하지 않기 때문에 다음과 같이 사용할 수 있습니다(Python 3.2+).

와 유사하다str.format(**mapping), 매핑은 에 복사되지 않고 직접 사용됩니다.이것은 예를 들어 매핑이 다음과 같은 경우 유용합니다.dict서브클래스

즉, 예를 들어 a를 사용할 수 있습니다.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)

내 Python 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'

네스트된 따옴표 안에 다른 따옴표를 사용해야 합니다.이 접근법의 또 다른 장점은 포맷 메서드를 호출하는 것보다 훨씬 빠르다는 것입니다.

이 질문은 Python 3에만 해당되므로 Python 3.6 이후 사용 가능한 새로운 f-string 구문을 사용해 보겠습니다.

>>> geopoint = {'latitude':41.123,'longitude':71.091}
>>> print(f'{geopoint["latitude"]} {geopoint["longitude"]}')
41.123 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

대부분의 응답은 dict 값만 포맷했습니다.

키의 형식을 문자열로 지정할 경우 dict.items()사용할 수 있습니다.

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

출력:

('118', 41.123'), ('118', 71.091)

임의 형식으로 형식을 지정하는 경우, 즉 튜플과 같은 키 값을 표시하지 않습니다.

from functools import reduce
print("{} is {} and {} is {}".format(*reduce((lambda x, y: x + y), [list(item) for item in geopoint.items()])))

출력:

위도는 41.123, 경도는 71.091입니다.

format_map을 사용하여 원하는 작업을 수행합니다.

print('{latitude} {longitude}'.format_map(geopoint))

이것은 라는 장점이 있습니다.

  • 은 매개 : 매개 변수)로 하지 않아도 .**geopoint that) 및 ) ) ) )
  • 형식 문자열은 지정된 맵에만 액세스할 수 있으며 변수의 전체 범위(F 스트링과 비교)는 사용할 수 없습니다.

언급URL : https://stackoverflow.com/questions/5952344/how-do-i-format-a-string-using-a-dictionary-in-python-3-x

반응형