programing

인수가있는 여러 줄 문자열.

shortcode 2021. 1. 17. 11:16
반응형

인수가있는 여러 줄 문자열. 신고하는 방법?


내가 만들고 싶은 인수가 포함 된 매우 긴 문자열이 있다고 가정 해 보겠습니다. 나는 당신이 여러 줄 문자열을 만들 수 있다는 것을 안다.

cmd = """line 1
      line 2
      line 3"""

하지만 이제 1, 2, 3을 인수로 전달하고 싶다고 가정 해 보겠습니다.

이것은 작동합니다

cmd = """line %d
      line %d
      line %d""" % (1, 2, 3)

그러나 30 개 이상의 인수가있는 매우 긴 문자열이있는 경우 이러한 인수를 여러 줄로 전달할 수있는 방법은 무엇입니까? 한 줄로 전달하면 여러 줄 문자열을 만들려는 목적조차 상실됩니다.

도움과 통찰력에 대해 미리 감사드립니다.


괄호 (와 쉼표 의 줄 연속 속성을 남용 할 수 있습니다 ,.

cmd = """line %d
      line %d
      line %d""" % (
      1,
      2,
      3)

str.format()명명 된 인수를 허용 하는 함수를 사용할 수 있습니다 .

'''line {0}
line {1}
line {2}'''.format(1,2,3)

당신은 물론 파이썬의 사용이 확장 할 수 *args당신이에 통과 할 수 있도록 구문을 tuple하거나 list:

args = (1,2,3)
'''line {0}
line {1}
line {2}'''.format(*args)

인수의 이름을 지능적으로 지정할 수 있다면 가장 강력한 솔루션 (가장 타이핑 집약적이지만)은 Python의 **kwargs구문을 사용 하여 사전을 전달하는 것입니다.

args = {'arg1':1, 'arg2':2, 'arg3':3}
'''line {arg1}
line {arg2}
line {arg3}'''.format(**args)

str.format()미니 언어 에 대한 자세한 내용은 여기를 참조하십시오 .


string.format ()-Function이있는 또 다른 변형입니다.

s = "{0} " \
    "{1} " \
    "{2}" \
    .format("Hello", "world", "from a multiline string")    
print(s)

가장 쉬운 방법은 리터럴 문자열 보간 을 사용하는 것입니다 (Python 3.6부터 사용 가능하고 모든 인수가 범위에 있다고 가정).

cmd = f"""line {1}
      line {2}
      line {3}"""

삽입 된 동일한 줄에 인수를 가지려면 다음과 같이 할 수 있습니다.

cmd = "line %d\n"%1 +\
      "line %d\n"%2 +\
      "line %d\n"%3

[편집 :] 첫 번째 댓글에 대한 답장으로 다음과 같이 생각했습니다.

cmd = "\n".join([
      "line %d"%1,
      "line %d"%2,
      "line %d"%3])

으로 @Chinmay Kanchi는 말한다 , 당신은 할 수 있습니다 :

'''line {0}
line {1}
line {2}'''.format(1,2,3)

그러나 새 줄에서 완전히 왼쪽으로 정렬되어야하는 정렬이 어리석어 보인다고 생각합니다. 특히 이미 여러 수준 들여 쓰기를 수행하는 경우에는 다음과 같이 작성하는 것이 좋습니다.

'''line {0}
   line {1}
   line {2}'''.format(1,2,3)

작동하지만 잘못되었습니다! 그것은 왼쪽 모든 공간을 해석 line {1}하고 line {2}그래서 바보를 볼 것이다 인쇄, 실제 공간으로를 :

1
   2
   3

대신에

1
2
3

따라서 해결 방법은 +연산자 를 사용하여 연결하고 연결된 문자열을 괄호로 묶고 다음과 같이 명시적인 줄 바꿈 ( \n) 문자를 사용하는 것입니다.

('line {0}\n' + 
 'line {1}\n' +
 'line {2}').format(1,2,3)

완벽합니다 (내 의견으로는)! 이제 인쇄하면 소스 코드와 실제 문자열 모두에서 멋지고 정렬됩니다.

전체 예 :

추악한 소스 코드!

num1 = 7
num2 = 100
num3 = 75.49

# Get some levels of indentation to really show the effect well.
# THIS IS *UGLY*! Notice the weird forced-left-align thing for the string I want to print!
if (True):
    if (True):
        if (True):
            # AAAAAH! This is hard to look at!
            print('''num1 = {}
num2 = {}
num3 = {}'''.format(num1, num2, num3))

            # More lines of code go here
            # etc
            # etc

산출:

num1 = 7
num2 = 100
num3 = 75.49

예쁜 예! Ahh, 소스 코드에서보기에 너무 좋습니다. :)

이것이 내가 선호하는 것입니다.

# Get some levels of indentation to really show the effect well.
if (True):
    if (True):
        if (True):
            # IMPORTANT: the extra set of parenthesis to tie all of the concatenated strings together here is *required*!
            print(('num1 = {}\n' + 
                   'num2 = {}\n' + 
                   'num3 = {}')
                   .format(num1, num2, num3))

            # More lines of code go here
            # etc
            # etc

산출:

num1 = 7
num2 = 100
num3 = 75.49

2019 년 5 월 21 일 업데이트 : 때때로 "추악한"여러 줄 문자열이 정말 최선의 방법입니다!

그래서 저는 Python을 사용하여 텍스트 기반 구성 파일에서 C 헤더 및 소스 (.h / .c) 파일자동 생성 해 왔으며 이를 상당량 수행 한 후 단순히 복사의 이점이 있다는 결론을 내 렸습니다. 구성 파일의 큰 텍스트를 내 Python 스크립트에 붙여 넣는 것은 "추악"요소보다 큽니다.

따라서 예를 들어 큰 여러 줄의 복사 붙여 넣기 문자열이 필요할 때 다음을 수행하는 것이 선호되는 방법이라고 결정했습니다.

옵션 1 :
-전체 긴 문자열 주위에 괄호를 사용 """하여 새 줄에 여는 것을 허용합니다.

# Get some levels of indentation to still show the "ugliness" effect.
if (True):
    if (True):
        if (True):
            header = (
"""
/*
my custom file header info here
*/

#pragma once

#include "{}"

const {} {};
""").format(include, struct_t, struct)

            print("header =" + header)

옵션 2 :
-괄호는 없지만 """자체 줄에 닫는 표시

# Get some levels of indentation to still show the "ugliness" effect.
if (True):
    if (True):
        if (True):
            header = """
/*
my custom file header info here
*/

#pragma once

#include "{}"

const {} {};
""".format(include, struct_t, struct)

            print("header =" + header)

옵션 3 :
-전체 문자열을 괄호로 묶지 """않고 문자열 내용과 같은 줄에 닫아서 \n끝에 (잠재적으로 바람직하지 않은) 추가를 방지 합니다.
-단, format(길이가 긴 경우 에는 나머지 부분을 새 줄 (또는 여러 줄)에 넣으십시오 .

# Get some levels of indentation to still show the "ugliness" effect.
if (True):
    if (True):
        if (True):
            header = """
/*
my custom file header info here
*/

#pragma once

#include "{}"

const {} {};""".format(
    include, struct_t, struct) # indentation here can literally be *anything*, but I like to indent 1 level; since it's inside parenthesis, however, it doesn't matter

            print("header =" + header)

산출:

  • 옵션 1과 2는 정확히 동일한 출력을 생성하며 \n문자열의 맨 끝에 추가 로 대부분의 경우 괜찮습니다.
  • 옵션 3은 귀하의 경우에 바람직하지 않은 경우 문자열 맨 끝에 여분 없다는 제외하고 옵션 1 및 2와 동일한 출력을 생성합니다.\n
  • 옵션 1, 2 또는 3을 사용하는지 여부는 실제로 중요하지 않습니다. \n바로 위에서 언급 한 추가 기능 을 제외하고는 이 시점에서 사용자 선호도 일뿐입니다.

위의 옵션 1, 2, 3에서 인쇄 한 내용입니다.

/*
my custom file header info here
*/

#pragma once

#include "<stdint.h>"

const my_struct_t my_struct;


모든 것을 하나로 모으기 : "pretty"와 "ugly"방법을 함께 사용 하여 모듈에 대한 문서화 문서를 인쇄하는 데모에서 최상의 결과를 얻으십시오 !

다음은 각각의 장점을 최대한 활용하기 위해 위에 제시된 "pretty"및 "ugly"여러 줄 문자열 메서드를 모두 사용하는 기본 예입니다. 또한 모듈을 문서화하기 위해 모듈 "독 스트링"을 사용하고 인쇄하는 방법도 보여줍니다. """기반 멀티 라인 기법이 어떻게 우리에게 큰 간격을 주는지 주목 하세요. 왜냐하면 제가 아래 에서 한 방식은 문자열이 쓰여지는 방식이기 때문에 \n열기 후 """와 닫기 전에 자동 개행 ( )이 """있기 때문입니다.

# PRETTY, AND GOOD.
print("\n\n" + 
      "########################\n" + 
      "PRINT DOCSTRING DEMO:\n" + 
      "########################")

import sys

def printDocstrings():
    """
    Print all document strings for this module, then exit.
    Params:  NA
    Returns: NA
    """

    # A LITTLE BIT UGLY, BUT GOOD! THIS WORKS GREAT HERE!
    print("""
---------------------
Module Documentation:
---------------------
printDocstrings:{}
myFunc1:{}
class Math:{}
    __init__:{}
    add:{}
    subtract:{}""".format(
        printDocstrings.__doc__,
        myFunc1.__doc__,
        Math.__doc__,
        Math.__init__.__doc__,
        Math.add.__doc__,
        Math.subtract.__doc__))

    sys.exit()

def myFunc1():
    """
    Do something.
    Params:  NA
    Returns: NA
    """
    pass

class Math:
    """
    A basic "math" class to add and subtract
    """

    def __init__(self):
        """
        New object initialization function.
        Params:  NA
        Returns: NA
        """
        pass

    def add(a, b):
        """
        Add a and b together.
        Params:  a   1st number to add
                 b   2nd number to add
        Returns: the sum of a + b
        """
        return a + b

    def subtract(a, b):
        """
        Subtract b from a.
        Params:  a   number to subtract from
                 b   number to subtract
        Returns: the result of a - b
        """
        return a - b

printDocstrings() 

출력 :
-이 방식으로 인쇄 할 때 독 스트링의 탭, 줄 바꿈 및 간격이 모두 자동으로 유지되므로 모든 것이 자동으로 얼마나 예쁘고 잘 포맷되었는지 확인하십시오!


########################  
PRINT DOCSTRING DEMO:  
########################  

---------------------  
Module Documentation:  
---------------------  
printDocstrings:  
    Print all document strings for this module, then exit.  
    Params:  NA  
    Returns: NA  

myFunc1:  
    Do something.  
    Params:  NA  
    Returns: NA  

class Math:  
    A basic "math" class to add and subtract  

    __init__:  
        New object initialization function.  
        Params:  NA  
        Returns: NA  

    add:  
        Add a and b together.  
        Params:  a   1st number to add  
                 b   2nd number to add  
        Returns: the sum of a + b  

    subtract:  
        Subtract b from a.  
        Params:  a   number to subtract from  
                 b   number to subtract  
        Returns: the result of a - b  


참조 :

  1. Python 독 스트링 : https://www.geeksforgeeks.org/python-docstrings/

    • Note: you can also use the help() method to access a module or class's documentation (but in an interactive manner), as shown in the link above, like this:

      help(Math)  # to interactively display Class docstring
      help(Math.add)  # to interactively display method's docstring 
      

This works for me:

cmd = """line %d
      line %d
      line %d""" % (
          1,
          2,
          3
      )

You may use textwrap.dedent to remove leading spaces from lines:

import textwrap

cmd = str.strip(textwrap.dedent(
    '''
        line {}
            line with indent
        line {}
        line {}
    '''
    .format(1, 2, 3)))

This results in:

line 1
    line with indent
line 2
line 3

Here is the simplest version, which is also IDE-friendly in terms of checking format arguments:

cmd = (
    'line {}\n'
    'line {}\n'
    'line {}\n'
    .format(1, 2, 3))

Multiline arguments version:

cmd = (
    'line {}\n'
    'line {}\n'
    'line {}\n'
    .format(
        'very very very very very very very very very long 1',
        'very very very very very very very very very long 2',
        'very very very very very very very very very long 3',
    )
)

ReferenceURL : https://stackoverflow.com/questions/10985603/multi-line-string-with-arguments-how-to-declare

반응형