programing tip

Python에서 형식 문자열 및 명명 된 인수

itbloger 2020. 11. 15. 10:58
반응형

Python에서 형식 문자열 및 명명 된 인수


사례 1 :

"{arg1} {arg2}".format (10, 20)

KeyError: 'arg1'명명 된 인수를 전달하지 않았기 때문에 줄 것 입니다.

사례 2 :

"{arg1} {arg2}".format(arg1 = 10, arg2 = 20)

이제 명명 된 인수를 전달했기 때문에 제대로 작동합니다. 그리고 그것은 인쇄'10 20'

사례 3 :

그리고 잘못된 이름을 전달하면 KeyError: 'arg1'

 "{arg1} {arg2}".format(wrong = 10, arg2 = 20)

그러나,

사례 4 :

명명 된 인수를 잘못된 순서로 전달하면

"{arg1} {arg2}".format(arg2 = 10, arg1 = 20)

효과가있다...

그리고 그것은 인쇄 '20 10'

내 질문은 이것이 작동하는 이유 와이 경우 명명 된 인수사용하는 이유 입니다.


명명 교체 필드합니다 ( {...}A의 부분 형식 문자열 에 대한 일치) 키워드 인수 받는 .format()방법, 그리고 위치 인수 .

키워드 인수는 사전의 키와 같습니다. 이름 과 일치하므로 순서는 중요하지 않습니다 .

위치 인수 와 일치 시키 려면 숫자를 사용하십시오.

"{0} {1}".format(10, 20)

Python 2.7 이상에서는 숫자를 생략 할 수 있습니다. {}교체 필드는 자동 번호 서식 문자열의 외관의 순서대로 :

"{} {}".format(10, 20) 

형식화 문자열은 위치 키워드 인수 일치 할 수 있으며 인수를 여러 번 사용할 수 있습니다.

"{1} {ham} {0} {foo} {1}".format(10, 20, foo='bar', ham='spam')

형식 문자열 사양 에서 인용 :

FIELD_NAME 자체는 시작 arg_name 중 하나입니다 숫자 또는 키워드 . 숫자이면 위치 인수를, 키워드이면 명명 된 키워드 인수를 참조합니다.

내 강조.

큰 서식 지정 문자열을 생성하는 경우 명명 된 대체 필드를 사용하는 것이 훨씬 더 읽기 쉽고 유지 관리하기 쉽습니다. 따라서 인수를 계속 계산하고 결과 문자열의 위치를 ​​파악할 필요가 없습니다.

또한 **keywords호출 구문을 사용하여 기존 사전을 형식에 적용하여 CSV 파일을 형식화 된 출력으로 쉽게 변환 할 수 있습니다.

import csv

fields = ('category', 'code', 'price', 'description', 'link', 'picture', 'plans')
table_row = '''\
    <tr>
      <td><img src="{picture}"></td>
      <td><a href="{link}">{description}</a> ({price:.2f})</td>
   </tr>
'''

with open(filename, 'rb') as infile:
    reader = csv.DictReader(infile, fieldnames=fields, delimiter='\t')
    for row in reader:
        row['price'] = float(row['price'])  # needed to make `.2f` formatting work
        print table_row.format(**row)

여기에서, picture, link, descriptionprice의 모든 열쇠 row사전, 그리고 훨씬 쉽게 나는를 적용 할 때 어떻게되는지에 row서식 문자열.


추가 혜택은 다음과 같습니다.

  • 당신은 인수의 순서에 대해 걱정할 필요가 없습니다 . 포맷터에 이름으로 표시된대로 문자열의 올바른 위치에 놓입니다.
  • You can put the same argument in a string twice, without having to repeat the argument. E.g. "{foo} {foo}".format(foo="bar") gives 'bar bar'

Note that you can give extra arguments without causing errors as well. All this is especially useful when

  • you change the string formatter later on with less changes and thus smaller posibility for mistakes. If it does not contain new named arguments, the format function will still work without changing the arguments and put the arguments where you indicate them in the formatter.
  • you can have multiple formatter strings sharing a set of arguments. In these case you could for instance have a dictionary with the all arguments and then pick them out in the formatter as you need them.

E.g.:

>d = {"foo":"bar", "test":"case", "dead":"beef"}
>print("I need foo ({foo}) and dead ({dead})".format(**d))
>print("I need test ({test}) and foo ({foo}) and then test again ({test})".format(**d))
I need foo (bar) and dead (beef)
I need test (case) and foo (bar) and then test again (case)

참고URL : https://stackoverflow.com/questions/17895835/format-strings-and-named-arguments-in-python

반응형