2016-07-27 3 views
0

파이썬의 string.Template 클래스 사용 - 공백이 포함 된 사전의 필드에 어떻게 $ {}을 사용할 수 있습니까?Python string.Template : 공백이 포함 된 필드 바꾸기

예.

t = string.Template("hello ${some field}") 
d = { "some field": "world" } 
print(t.substitute(d)) # Returns "invalid placeholder in string" 

편집 : 여기에주의해야 할 점이 모든 변수는 괄호 (그렇지 않으면 모든 공간이 구분 된 단어가 일치하는 것)에 싸여 될 필요가 있다는 것을 함께, 내가 얻을 수있는 가장 가까운입니다.

class MyTemplate(string.Template): 
    delimiter = '$' 
    idpattern = '[_a-z][\s_a-z0-9]*' 

t = MyTemplate("${foo foo} world ${bar}") 
s = t.substitute({ "foo foo": "hello", "bar": "goodbye" }) 
# hello world goodbye 

답변

0

경우에 따라 다른 사람에게 도움이 될 수 있습니다. 파이썬 3에서는이 format_map을 사용할 수 있습니다 : 문서에서

t = "hello {some field}" 
d = { "some field": "world" } 
print(t.format_map(d)) 

# hello world 
+0

아를 사용할 수 있다고이 좋은 보인다 - 그것은 파이썬 3 만입니까? 나는 아마도 파이썬 2.7x 지원에 대한 필요성을 언급 했어야했다. – funseiki

+0

'str'의'.format' 메소드를 사용할 수있다 :'print ('hello {some field}'. format (** d))' –

0

우리가 템플릿 옵션

https://docs.python.org/dev/library/string.html#template-strings

import string 

class MyTemplate(string.Template): 
    delimiter = '%' 
    idpattern = '[a-z]+ [a-z]+' 

t = MyTemplate('%% %with_underscore %notunderscored') 
d = { 'with_underscore':'replaced', 
     'notunderscored':'not replaced', 
     } 

print t.safe_substitute(d) 
+0

I ' 이걸로 조금 혼란 스럽네요. 어떤 결과물을 얻으 려구요? 방금이 코드를 실행하고 "% % with_underscore가 대체되지 않음"을 얻었습니다. – funseiki

+0

이것은 모든 변수가 {}로 묶여있는 한 원하는 것에 매우 가깝습니다. (답을이 항목이나 비슷한 것으로 업데이트하면, idpattern = '[_a-z] [_ \ sa-z0-9] *' – funseiki

관련 문제