ProgramingTip

고정 너비를 정렬하는 방법은 무엇입니까?

bestdevel 2020. 12. 26. 15:57
반응형

고정 너비를 정렬하는 방법은 무엇입니까?


고정 너비의 텍스트 열을 원하지만 그것은 모두 왼쪽 대신에 채워집니다 !!?

 sys.stdout.write("%6s %50s %25s\n" % (code, name, industry))

생산하다

BGA                                BEGA CHEESE LIMITED   Food Beverage & Tobacco
BHP                               BHP BILLITON LIMITED                 Materials
BGL                               BIGAIR GROUP LIMITED Telecommunication Services
BGG           BLACKGOLD INTERNATIONAL HOLDINGS LIMITED                    Energy

하지만 우리는 원한다

BGA BEGA CHEESE LIMITED                                Food Beverage & Tobacco
BHP BHP BILLITON LIMITED                               Materials
BGL BIGAIR GROUP LIMITED                               Telecommunication Services
BGG BLACKGOLD INTERNATIONAL HOLDINGS LIMITED           Energy

-왼쪽 맞춤을 위해 크기 요구 사항을 접두사로 지정할 수 있습니다 .

sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))

이 버전은 str.format 메소드를 사용합니다 .

Python 2.7 이상

sys.stdout.write("{:<7}{:<51}{:<25}\n".format(code, name, industry))

Python 2.6 버전

sys.stdout.write("{0:<7}{1:<51}{2:<25}\n".format(code, name, industry))

최신 정보

이전에는 문서에서 언어에서 언어에서 % 연산자에 대한 설명이 제거됩니다. 이 문은 문서에서 확대 .


sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))

참고로 너비를 변수로 만들 수 있습니다. *-s

>>> d = "%-*s%-*s"%(25,"apple",30,"something")
>>> d
'apple                    something                     '

-50%대신 사용 +50%하면 정렬됩니다.


확실히 선호 나는 format가 매우 유연하고 쉽게 정의하여 user-정의 클래스를 확장 할 수있는,을 더 방법 __format__하거나 str또는 repr표현. 간단하게 유지하기 위해 print다음 예제에서 사용 하고있는 sys.stdout.write.

간단한 예 : 정렬 / 채우기

#Justify / ALign (left, mid, right)
print("{0:<10}".format("Guido"))    # 'Guido     '
print("{0:>10}".format("Guido"))    # '     Guido'
print("{0:^10}".format("Guido"))    # '  Guido   '

는 옆에 우리 추가 할 수 align있습니다 지정

^, <>채우기 문자는 다른 문자로 공간을 대체 할

print("{0:.^10}".format("Guido"))    #..Guido...

다중 입력 예제 : 많은 입력 정렬 및 채우기

print("{0:.<20} {1:.>20} {2:.^20} ".format("Product", "Price", "Sum"))
#'Product............. ...............Price ........Sum.........'

고급 예

사용자 정의 클래스가있는 경우 다음과 같이 해당 클래스 str또는 repr표현을 정의 할 수 있습니다 .

class foo(object):
    def __str__(self):
        return "...::4::.."

    def __repr__(self):
        return "...::12::.."

이제 !s(str) 또는 !r(repr)을 사용하여 정의 된 메서드를 호출하도록 지시 할 수 있습니다 . 정의 된 것이 운영하는 Python은 __format__기본적으로 사용할 수 있습니다. x = foo ()

print "{0!r:<10}".format(x)    #'...::12::..'
print "{0!s:<10}".format(x)    #'...::4::..'

출처 : Python Essential Reference, David M. Beazley, 4 판


새로운 인기와 함께 F- 문자열필요한 정렬 3.6 , 우리가 어떻게해야할까요?

string = "Stack Overflow"
print(f"{string:<16}..")
Stack Overflow  ..

가변 패딩 길이가있는 경우 :

k = 20
print(f"{string:<{k}}..")
Stack Overflow      .. 

f-Ki 더 읽을 수 있습니다.


이것은 내 능력 발휘에서 작동했습니다.

print "\t%-5s %-10s %-10s %-10s %-10s %-10s %-20s"  % (thread[0],thread[1],thread[2],thread[3],thread[4],thread[5],thread[6])

약간 더 읽기 쉬운 대안 솔루션 :
sys.stdout.write(code.ljust(5) + name.ljust(20) + industry)

ljust(#ofchars)고정 너비 문자 사용하며 다른 솔루션처럼 동적으로 조정되지 않습니다.

참조 URL : https://stackoverflow.com/questions/12684368/how-to-left-align-a-fixed-width-string

반응형