programing

고정된 너비로 줄을 인쇄하는 방법은 무엇입니까?

coolbiz 2023. 7. 9. 21:43
반응형

고정된 너비로 줄을 인쇄하는 방법은 무엇입니까?

이 코드가 있습니다(모든 순열이 문자열에서 발생한 경우 인쇄).

def splitter(str):
    for i in range(1, len(str)):
        start = str[0:i]
        end = str[i:]
        yield (start, end)
        for split in splitter(end):
            result = [start]
            result.extend(split)
            yield result    

el =[];

string = "abcd"
for b in splitter("abcd"):
    el.extend(b);

unique =  sorted(set(el));

for prefix in unique:
    if prefix != "":
        print "value  " , prefix  , "- num of occurrences =   " , string.count(str(prefix));

문자열 변수에 있는 모든 순열 발생을 인쇄하고 싶습니다.

순열 길이가 동일하지 않기 때문에 폭을 수정하여 이와 같은 것이 아닌 멋진 방식으로 인쇄하고 싶습니다.

value   a - num of occurrences =    1
value   ab - num of occurrences =    1
value   abc - num of occurrences =    1
value   b - num of occurrences =    1
value   bc - num of occurrences =    1
value   bcd - num of occurrences =    1
value   c - num of occurrences =    1
value   cd - num of occurrences =    1
value   d - num of occurrences =    1

사용 방법format하기 위해서?

다음 게시물을 찾았지만 영숫자 문자열과 잘 맞지 않았습니다.

python 문자열 형식 고정 너비

파이썬으로 고정 길이 설정

을 사용합니다.str.format훨씬 더 우아함:

>>> '{0: <5}'.format('s')
's    '
>>> '{0: <5}'.format('ss')
'ss   '
>>> '{0: <5}'.format('sss')
'sss  '
>>> '{0: <5}'.format('ssss')
'ssss '
>>> '{0: <5}'.format('sssss')
'sssss'

문자열을 올바른 용도로 정렬하려는 경우>대신에<:

>>> '{0: >5}'.format('ss')
'   ss'

편집 1: 댓글에 언급된 것처럼:0'{0: <5}'전달된 인수의 인덱스를 나타냅니다.str.format().


편집 2: python3에서는 f-string도 사용할 수 있습니다.

sub_str='s'
for i in range(1,6):
    s = sub_str*i
    print(f'{s:>5}')
    
'    s'
'   ss'
'  sss'
' ssss'
'sssss'

또는:

for i in range(1,5):
    s = sub_str*i
    print(f'{s:<5}')
's    '
'ss   '
'sss  '
'ssss '
'sssss'

주목할 만한 것은, 위의 몇몇 장소에서,' '인쇄된 문자열의 너비를 강조하기 위해 (단일 따옴표)가 추가되었습니다.

EDIT 2013-12-11 - 이 답변은 매우 오래되었습니다.이것은 여전히 유효하고 정확하지만, 이것을 보는 사람들은 새로운 형식 구문을 선호해야 합니다.

다음과 같은 문자열 형식을 사용할 수 있습니다.

>>> print '%5s' % 'aa'
   aa
>>> print '%5s' % 'aaa'
  aaa
>>> print '%5s' % 'aaaa'
 aaaa
>>> print '%5s' % 'aaaaa'
aaaaa

기본적으로:

  • %캐릭터는 파이썬에게 토큰을 대체해야 할 것이라고 알립니다.
  • s문자는 python에게 토큰이 문자열이 될 것이라고 알립니다.
  • 5(또는 원하는 숫자)는 파이썬에 최대 5자의 공백으로 문자열을 패딩하도록 알려줍니다.

구체적인 사례에서 구현 가능성은 다음과 같습니다.

>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
...     print 'value %3s - num of occurances = %d' % item # %d is the token of integers
... 
value   a - num of occurances = 1
value  ab - num of occurances = 1
value abc - num of occurances = 1

측면 참고: 모듈의 존재를 알고 있는지 궁금합니다.예를 들어 다음과 같이 한 줄로 모든 조합의 목록을 얻을 수 있습니다.

>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']

그리고 당신은 를 사용하여 발생 횟수를 얻을 수 있습니다.combinations와 함께count().

원래는 @0x90님의 답변에 편집으로 게시되었으나, 게시물의 본래 의도에서 벗어난다는 이유로 거절당하여 댓글이나 답변으로 게시할 것을 추천받았기 때문에 여기에 짧은 글을 포함합니다.

@0x90의 답변 외에도 너비에 대한 변수를 사용하여 구문을 보다 유연하게 만들 수 있습니다(@user2763554의 설명에 따름).

width=10
'{0: <{width}}'.format('sss', width=width)

또한 숫자만 사용하고 전달된 인수의 순서에 의존함으로써 이 표현을 더 간략하게 만들 수 있습니다.format:

width=10
'{0: <{1}}'.format('sss', width)

또는 최대, 잠재적으로 비단조적으로 암시적이지 않은 압축성을 위해 모든 숫자를 생략합니다.

width=10
'{: <{}}'.format('sss', width)

2017-05-26 업데이트

Python 3.6에 포맷된 문자열 리터럴("f-strings")이 도입됨에 따라 이전에 정의된 변수에 보다 간략한 구문으로 액세스할 수 있게 되었습니다.

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'

이는 문자열 형식 지정에도 적용됩니다.

>>> width=10
>>> string = 'sss'
>>> f'{string: <{width}}'
'sss       '

format확실히 가장 우아한 방법이지만, 파이썬의 방법으로는 사용할 수 없는 페이크입니다.logging모듈을 사용하여 수행할 수 있는 방법은 다음과 같습니다.%형식 지정:

formatter = logging.Formatter(
    fmt='%(asctime)s | %(name)-20s | %(levelname)-10s | %(message)s',
)

자, 그.-정렬을 , 왼쪽 정렬및숫나자타다니 앞의 를 나타냅니다.s고정 너비를 나타냅니다.

일부 샘플 출력:

2017-03-14 14:43:42,581 | this-app             | INFO       | running main
2017-03-14 14:43:42,581 | this-app.aux         | DEBUG      | 5 is an int!
2017-03-14 14:43:42,581 | this-app.aux         | INFO       | hello
2017-03-14 14:43:42,581 | this-app             | ERROR      | failed running main

자세한 내용은 다음 문서를 참조하십시오. https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

이렇게 하면 한 번에 여러 요소를 인쇄할 때 고정 길이를 유지하는 데 도움이 됩니다.

25s25개의 공백으로 문자열을 포맷합니다. 기본적으로 정렬된 상태로 둡니다.

5d5개의 공백을 예약한 정수 형식을 지정합니다. 기본적으로 오른쪽으로 정렬됩니다.

members=["Niroshan","Brayan","Kate"]
print("__________________________________________________________________")
print('{:25s} {:32s} {:35s} '.format("Name","Country","Age"))
print("__________________________________________________________________")
print('{:25s} {:30s} {:5d} '.format(members[0],"Srilanka",20))
print('{:25s} {:30s} {:5d} '.format(members[1],"Australia",25))
print('{:25s} {:30s} {:5d} '.format(members[2],"England",30))
print("__________________________________________________________________")

그리고 이것은 인쇄될 것입니다.

__________________________________________________________________
Name                      Country                          Age
__________________________________________________________________
Niroshan                  Srilanka                          20
Brayan                    Australia                         25
Kate                      England                           30
__________________________________________________________________
>>> print(f"{'123':<4}56789")
123 56789

찾았습니다ljust()그리고.rjust()고정된 너비로 문자열을 인쇄하거나 공백으로 Python 문자열을 채우는 데 매우 유용합니다.

예문

print('123.00'.rjust(9))
print('123456.89'.rjust(9))

# expected output  
   123.00
123456.89

에는 당의경우, 당은사니다용합을 합니다.fstring

for prefix in unique:
    if prefix != "":
        print(f"value  {prefix.ljust(3)} - num of occurrences = {string.count(str(prefix))}")

예상 출력

value  a   - num of occurrences = 1
value  ab  - num of occurrences = 1
value  abc - num of occurrences = 1
value  b   - num of occurrences = 1
value  bc  - num of occurrences = 1
value  bcd - num of occurrences = 1
value  c   - num of occurrences = 1
value  cd  - num of occurrences = 1
value  d   - num of occurrences = 1

을 변경할 수 .3최대 길이의 순열 문자열로 변환합니다.

f 문자열을 사용하면 형식과 함께 작동합니다.

https://scientificallysound.org/2016/10/17/python-print3/

f'{some_variable:<20s}{some_variable:_<20s}{some_variable:<20대>

언급URL : https://stackoverflow.com/questions/8450472/how-to-print-a-string-at-a-fixed-width

반응형