어떻게하면 파이썬을 사용하여 쉽게 변수를 문자열로 확장 할 수 있습니까?
대신 : print "%s is a %s %s that %s" % (name, adjective, noun, verb)
나는 효과를 내기 위해 뭔가를 할 수 있기를 바란다 : print "{name} is a {adjective} {noun} that {verb}"
어떻게하면 파이썬을 사용하여 쉽게 변수를 문자열로 확장 할 수 있습니까?
대신 : print "%s is a %s %s that %s" % (name, adjective, noun, verb)
나는 효과를 내기 위해 뭔가를 할 수 있기를 바란다 : print "{name} is a {adjective} {noun} that {verb}"
"{name} is a {adjective} {noun} that {verb}".format(**locals())
locals()
이 (사전으로) 현재의 네임 스페이스에 대한 참조를 제공합니다.**locals()
은 해당 사전을 키워드 인수 (f(**{'a': 0, 'b': 1})
은 f(a=0, b=1)
)로 압축 해제합니다..format()
은 "the new string formatting"입니다. 이는 더 많은 작업을 수행 할 수 있습니다 (예 : 첫 번째 위치 인수의 이름 속성에 대해 {0.name}
).또는 string.template
(이중 문자 {'name': name, ...}
dict 리터럴을 피하려면 로컬로).
는 수행
print name,'is a',adjective,noun,'that',verb
파이썬 3의 경우 :
print(name,'is a',adjective,noun,'that',verb)
문자열에 저장해야하는 경우 +
연산자로 연결해야하므로 공백을 삽입해야합니다. print
은 매개 변수 끝에 끝에 오는 쉼표가없는 한 모두 ,
에 공백을 삽입합니다.이 경우 쉼표가 생략됩니다.
result = name+' is a '+adjective+' '+noun+' that '+verb
주) (단지 – delnan
고정 덕분에 delnan) 괄호를 놓습니다. –
사용 Pyhon 2,이 대신 일부 문자열의 튜플을 인쇄하는 것이 string.Template
>>> from string import Template
>>> t = Template("$name is a $adjective $noun that $verb")
>>> t.substitute(name="Lionel", adjective="awesome", noun="dude", verb="snores")
'Lionel is a awesome dude that snores'
자세한 내용 및 옵션 : http://docs.python.org/library/stdtypes.html#string-formatting – Harmen
@ 하렘 : +1 링크를 실제로 찾고 있었지만 PEP를 먼저 찾았습니다. 내 검색 알고리즘에 결함이 있습니다. – delnan
함수에 locals()를 전달하는 것은 대개 매우 나쁜 생각입니다. 매개 변수 크리프 (creep)로 이어지며, 실제로 어떤 변수가 전달되고 실제로 어떤 지역 변수인지를 파악하는 것은 불가능합니다. –