본문 바로가기
파이썬

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

by º기록 2020. 10. 3.
반응형

저는 사전을 사용하여 문자열 형식을 지정하는 것을 좋아합니다. 사용중인 문자열 형식을 읽고 기존 사전을 활용할 수 있도록 도와줍니다. 예를 들면 :

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

그러나 동일한 작업을 수행하는 파이썬 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(f'{geopoint["latitude"]} {geopoint["longitude"]}')
41.123 71.091

바깥 쪽 작은 따옴표와 안쪽 큰 따옴표에주의하십시오 (다른 방법으로도 할 수 있습니다).

 

참조 페이지 https://stackoverflow.com/questions/5952344

 

 

반응형

댓글