Nice programing

인라인 변수로 여러 줄 Python 문자열을 어떻게 생성합니까?

nicepro 2020. 10. 13. 19:19
반응형

인라인 변수로 여러 줄 Python 문자열을 어떻게 생성합니까?


여러 줄로 된 Python 문자열 내에서 변수를 사용하는 깨끗한 방법을 찾고 있습니다. 다음을 수행하고 싶다고 가정합니다.

string1 = go
string2 = now
string3 = great

"""
I will $string1 there
I will go $string2
$string3
"""

$Python 구문에서 변수를 나타내는 Perl 과 비슷한 것이 있는지 확인하고 있습니다 .

그렇지 않다면-변수로 여러 줄 문자열을 만드는 가장 깨끗한 방법은 무엇입니까?


일반적인 방법은 format()기능입니다.

>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'

여러 줄 형식 문자열에서 잘 작동합니다.

>>> s = '''\
... This is a {length} example.
... Here is a {ordinal} line.\
... '''.format(length='multi-line', ordinal='second')
>>> print(s)
This is a multi-line example.
Here is a second line.

변수와 함께 사전을 전달할 수도 있습니다.

>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'

(구문 측면에서) 요청한 것과 가장 가까운 것은 템플릿 문자열 입니다. 예를 들면 :

>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'

format()기능은 쉽게 사용할 수 있고 가져 오기 라인이 필요하지 않기 때문에 더 일반적이라고 덧붙여 야합니다 .


참고 : Python에서 문자열 형식 지정을 수행하는 데 권장되는 방법 은 허용되는 답변에format() 설명 된대로 를 사용 하는 것 입니다. 이 답변은 지원되는 C 스타일 구문의 예로 유지됩니다.

# NOTE: format() is a better choice!
string1 = "go"
string2 = "now"
string3 = "great"

s = """
I will %s there
I will go %s
%s
""" % (string1, string2, string3)

print(s)

일부 읽기 :


여러 줄 또는 긴 한 줄 문자열 내의 변수에 Python 3.6의 f- 문자열사용할 수 있습니다 . 를 사용하여 개행 문자를 수동으로 지정할 수 있습니다 .\n

여러 줄 문자열의 변수

string1 = "go"
string2 = "now"
string3 = "great"

multiline_string = (f"I will {string1} there\n"
                    f"I will go {string2}.\n"
                    f"{string3}.")

print(multiline_string)

내가 거기 가서
내가 지금 갈 것이다

긴 한 줄 문자열의 변수

string1 = "go"
string2 = "now"
string3 = "great"

singleline_string = (f"I will {string1} there. "
                     f"I will go {string2}. "
                     f"{string3}.")

print(singleline_string)

나는 거기에 갈 것이다. 이제 갈거야. 큰.


또는 삼중 따옴표를 사용하여 여러 줄 f- 문자열을 만들 수도 있습니다.

multiline_string = f"""I will {string1} there.
I will go {string2}.
{string3}."""

이것이 당신이 원하는 것입니다.

>>> string1 = "go"
>>> string2 = "now"
>>> string3 = "great"
>>> mystring = """
... I will {string1} there
... I will go {string2}
... {string3}
... """
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, 'string3': 'great', '__package__': None, 'mystring': "\nI will {string1} there\nI will go {string2}\n{string3}\n", '__name__': '__main__', 'string2': 'now', '__doc__': None, 'string1': 'go'}
>>> print(mystring.format(**locals()))

I will go there
I will go now
great

A dictionary can be passed to format(), each key name will become a variable for each associated value.

dict = {'string1': 'go',
        'string2': 'now',
        'string3': 'great'}

multiline_string = '''I'm will {string1} there
I will go {string2}
{string3}'''.format(**dict)

print(multiline_string)


Also a list can be passed to format(), the index number of each value will be used as variables in this case.

list = ['go',
        'now',
        'great']

multiline_string = '''I'm will {0} there
I will go {1}
{2}'''.format(*list)

print(multiline_string)


Both solutions above will output the same:

I'm will go there
I will go now
great

참고URL : https://stackoverflow.com/questions/10112614/how-do-i-create-a-multiline-python-string-with-inline-variables

반응형