2017-10-24 16 views
1

식별자 값을 사전의 값으로 바꾸는 데 도움을 주시겠습니까? 그래서 코드는 123ABC, 난 단지 값을 변경할와 $ {1} 밥과 함께 $ {2} $ {} 안에있는 값은 단지 내가 만약 대체 할 수 있도록하려는문자열의 값을 파이썬 사전의 값으로 바꾸기

#string holds the value we want to output 
    s = '${1}_p${guid}s_${2}' 
    d = {1: 'bob', 2: '123abc', 3: 'CA', 4: 'smith' } 

다음과 같습니다 그런 다음 숫자를 사전의 값으로 대체하십시오.

output = 'bob_p${guid}s_123abc' 

템플릿 모듈을 사용해 보았지만 값이 부합하지 않았습니다.

+0

? 's'이 어떻게 형식화되었는지를 자유롭게 바꿀 수 있습니까? – mkrieger1

+0

시도한 내용과 작동하지 않은 내용을 보여줄 수 있습니까? – mkrieger1

+0

은 언제든지 편집 할 수있는 속성 파일에서 가져옵니다. – JanDoe2891

답변

-2

표준 문자열 .format()을 사용할 수 있습니다. Here은 관련 정보가 담긴 문서에 대한 링크입니다. 이 페이지에서 다음 인용문을 특히 유용하게 사용할 수 있습니다. 여기

"First, thou shalt count to {0}" # References first positional argument 
"Bring me a {}"     # Implicitly references the first positional argument 
"From {} to {}"     # Same as "From {0} to {1}" 
"My quest is {name}"    # References keyword argument 'name' 
"Weight in tons {0.weight}"  # 'weight' attribute of first positional arg 
"Units destroyed: {players[0]}" # First element of keyword argument 'players'. 

이 수정 코드는 .format() 방법을 사용하여 기반으로합니다.

# string holds the value we want to output 
d = {1: 'bob', 2: '123abc', 3: 'CA', 4: 'smith'} 

s = '' 
try: 
    s = '{0[1]}_p'.format(d) + '${guid}' + 's_{0[2]}'.format(d) 
except KeyError: 
    # Handles the case when the key is not in the given dict. It will keep the sting as blank. You can also put 
    # something else in this section to handle this case. 
    pass 
print s 
0

시도해보십시오. 그래서 사전에있는 각 키를 대체 할 부분을 알고 있습니다. 나는 그 코드가 자명하다고 생각한다.

s = '${1}_p${guid}s_${2}' 
d = {1: 'bob', 2: '123abc', 3: 'CA', 4: 'smith' } 

for i in d: 
    s = s.replace('${'+str(i)+'}',d[i]) 
print(s) 

출력 :

bob_p${guid}s_123abc 
1

사용 re.findall이 값을 교체해야 얻을 수 있습니다.

>>> import re 
>>> to_replace = re.findall('{\d}',s) 
>>> to_replace 
=> ['{1}', '{2}'] 

이제 to_replace 값을 통해 이동 .replace()을 수행합니다.

>>> for r in to_replace: 
     val = int(r.strip('{}')) 
     try:          #since d[val] may not be present 
       s = s.replace('$'+r, d[val]) 
     except: 
       pass 

>>> s 
=> 'bob_p${guid}s_123abc' 

#driver 값 : 당신이에서 문자열`s`를받을 수 있나요

IN : s = '${1}_p${guid}s_${2}' 
IN : d = {1: 'bob', 2: '123abc', 3: 'CA', 4: 'smith' }