[python] Ruby의 문자열 보간에 해당하는 Python이 있습니까?

루비 예 :

name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."

성공적인 파이썬 문자열 연결은 나에게 장황하게 보입니다.



답변

Python 3.6은 Ruby의 문자열 보간과 유사한 리터럴 문자열 보간 을 추가 합니다. 해당 버전의 Python (2016 년 말 출시 예정)부터 “f-strings”에 표현식을 포함시킬 수 있습니다.

name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")

3.6 이전에는 가장 가까운 거리는

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())

%연산자는 파이썬에서 문자열 보간 에 사용될 수 있습니다 . 첫 번째 피연산자는 보간 할 문자열이며 두 번째 피연산자는 “매핑”을 포함하여 필드 이름을 보간 할 값에 매핑하는 등 다른 유형을 가질 수 있습니다. 여기서는 로컬 변수 사전을 사용하여 locals()필드 이름 name을 로컬 변수 값 에 매핑했습니다 .

.format()최신 Python 버전 의 방법을 사용하는 동일한 코드 는 다음과 같습니다.

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))

도있다 string.Template클래스 :

tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))


답변

Python 2.6.X부터 다음을 사용할 수 있습니다.

"my {0} string: {1}".format("cool", "Hello there!")


답변

파이썬에서 문자열 보간가능하게 하는 interpy 패키지를 개발했습니다 .

를 통해 설치하십시오 pip install interpy. 그런 다음 # coding: interpy파일 시작 부분에 줄 을 추가하십시오 !

예:

#!/usr/bin/env python
# coding: interpy

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n#{name}."


답변

파이썬의 문자열 보간은 C의 printf ()와 유사합니다

시도하면 :

name = "SpongeBob Squarepants"
print "Who lives in a Pineapple under the sea? %s" % name

태그 %sname변수 로 대체됩니다 . 인쇄 기능 태그를 살펴보십시오. http://docs.python.org/library/functions.html


답변

문자열 보간은 PEP 498에 지정된대로 Python 3.6에 포함됩니다 . 당신은 이것을 할 수있을 것입니다 :

name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? \n{name}')

스폰지 밥이 싫어서 작성하는 것이 약간 고통 스럽습니다. 🙂


답변

당신은 또한 이것을 가질 수 있습니다

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n{name}.".format(name=name)

http://docs.python.org/2/library/string.html#formatstrings


답변

import inspect
def s(template, **kwargs):
    "Usage: s(string, **locals())"
    if not kwargs:
        frame = inspect.currentframe()
        try:
            kwargs = frame.f_back.f_locals
        finally:
            del frame
        if not kwargs:
            kwargs = globals()
    return template.format(**kwargs)

용법:

a = 123
s('{a}', locals()) # print '123'
s('{a}') # it is equal to the above statement: print '123'
s('{b}') # raise an KeyError: b variable not found

추신 : 성능에 문제가있을 수 있습니다. 프로덕션 로그가 아닌 로컬 스크립트에 유용합니다.

중복 :