SORU
23 Mart 2010, Salı


Python için uygun girinti dizeleri çok satırlı

Bir işlev içinde Python çok satırlı dizeleri için uygun girinti nedir?

    def method():
        string = """line one
line two
line three"""

ya

    def method():
        string = """line one
        line two
        line three"""

ya da başka bir şey?

Türünün ilk örneği dize işlevi dışında asılı olması garip görünüyor.

Teşekkürler.

CEVAP
23 Mart 2010, Salı


Muhtemelen """ ile hizaya getirmek istiyor

def foo():
    string = """line one
             line two
             line three"""

Yeni satır ve boşluk dize kendisi dahil olduğundan, yeniden işle yeniden gerekir. Bunu yapmak istemezsin ve metin bir sürü varsa, bir metin dosyası içinde ayrı olarak saklamak isteyebilirsiniz. Bir metin dosyası uygulama için çalışmıyor ve yeniden işle yeniden yapmak istemiyorsanız, muhtemelen ile gitmek istiyorum

def foo():
    string = ("this is an "
              "implicitly joined "
              "string")

Eğer ihtiyacın yok parçaları kesmek için bir çok satırlı dize yeniden işle yeniden istiyorsanız, docstrings PEP 257 sunulan işlem sonrası için textwrap Modül veya teknik düşünmelisiniz:

def trim(docstring):
    if not docstring:
        return ''
    # Convert tabs to spaces (following the normal Python rules)
    # and split into a list of lines:
    lines = docstring.expandtabs().splitlines()
    # Determine minimum indentation (first line doesn't count):
    indent = sys.maxint
    for line in lines[1:]:
        stripped = line.lstrip()
        if stripped:
            indent = min(indent, len(line) - len(stripped))
    # Remove indentation (first line is special):
    trimmed = [lines[0].strip()]
    if indent < sys.maxint:
        for line in lines[1:]:
            trimmed.append(line[indent:].rstrip())
    # Strip off trailing and leading blank lines:
    while trimmed and not trimmed[-1]:
        trimmed.pop()
    while trimmed and not trimmed[0]:
        trimmed.pop(0)
    # Return a single string:
    return '\n'.join(trimmed)

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Artorius FullPower

    Artorius Ful

    29 Temmuz 2007
  • Kai Moosmann

    Kai Moosmann

    5 Temmuz 2006
  • Trulia

    Trulia

    29 Kasım 2006