공유 블로그

예를 들어

fo = 'test{test}{num}'

이런 식으로 있는데

print(fo.format(test='test',num='1'))

이런 식으로 줘야 됩니다.

그리고 기본적으로 딕셔너리 형태로 줄 수가 없습니다.

 

딕셔너리 형태 방법

일단 딕셔너리 형태로 주는 방법입니다.

test = {
    'test':'dd',
    'num': 1
}

fo = 'test{test}{num}'

print(fo.format(**test))

간단하게 **주면 됩니다. (또는 fo.format_map(test) 줄수도 있습니다.)

 

하지만 문제가 하나 더 있습니다.

 

만약 없는 딕셔너리 즉

 

test = {

    'test':'dd',

}

fo = 'test{test}{num}'

print(fo.format(**test))

test = {
    'test':'dd',
}
fo = 'test{test}{num}'
print(fo.format(**test))

 

이런 식으로 하면 에러가 납니다

하지만 방법 있습니다

default 값을 주는 방법입니다.

 

 

Default값 주는 방법

from string import Formatter

# .format형식 Default값 정의
class PartialFormatter(Formatter):
    # missing은 없는 키 값 정의
    # bad_fmt은 형식(타입 등)이 안맞을때 정의
    def __init__(self, missing='', bad_fmt='(포맷형식이 잘못됨!!)'):
        self.missing, self.bad_fmt=missing, bad_fmt

    def get_field(self, field_name, args, kwargs):
        # 찾을 수 없는 키 처리
        try:
            val=super(PartialFormatter, self).get_field(field_name, args, kwargs)
        except (KeyError, AttributeError):
            val=None,field_name 
        return val 

    def format_field(self, value, spec):
        # 잘못된 형식(타입 등) 처리
        if value==None: return self.missing
        try:
            return super(PartialFormatter, self).format_field(value, spec)
        except ValueError:
            if self.bad_fmt is not None: return self.bad_fmt   
            else: raise




# format에 사용되는 딕셔너리 정의
test = {
    'test':'dd',
}

# format초기값
fo = 'test{test}{num}'

# format Default 초기화(초기값 : '')
fmt=PartialFormatter()

# 사용법
print(fmt.format(fo,**test))

위와 같이 코드를 사용하게 되면 

딕셔너리에 없는 값은 무시하고 출력하게 됩니다.

'확인'에서 자세한 내용을 확인할수 있습니다.

 

출처 : https://stackoverflow.com/questions/20248355/how-to-get-python-to-gracefully-format-none-and-non-existing-fields

 

 

확인

더보기
키값 없을 때

 

형식 안 맞을 때

 

해당 내용은 아래 링크에 사용 되었습니다.

참고하시면 되겠습니다.

https://all-share-source-code.tistory.com/45

 

파이썬 selenium execute_script 스크립트 컨트롤 함수

파이썬 selenium execute_script는 JavaScript코드인 스크립트 형식으로 작동하게 됩니다. 그래서 사용할때 문자열로 작성하다 보니 자동 완성 안됨 과 코드가 길어지는 등 여러 단점이 있는데요 그걸 해

all-share-source-code.tistory.com

 

공유하기

facebook twitter kakaoTalk naver band kakaostory Copy URL