Break lines in a certain Python character space

Asked

Viewed 1,598 times

1

Hello, I created a program in Python to create a sequence of P.A., but I want the print of the result of the numbers to break after 100 characters, so the result stays inside the screen. someone can help me??

texto = 'Calculadora de Progressão Aritmética'
print('=' * 100)
print(f'{texto: ^100}')
print('=' * 100)
a1 = input('Digite o primeiro termo da P.A.: ')
r = input('Digite a razão da P.A.: ')
ter = input('Quantos termos da P.A. deseja visualizar? ')
cont = 0
if a1.isdigit() and r.isdigit() and ter.isdigit() or '-' in a1 or '-' in r:
    for i in range(0, int(ter)):
        cont = cont + 1
        if True:
            an = int(a1) + (cont - 1) * int(r)
        print(f'{an}', end=', ')
    print(f'sao os {ter} primeiros termos da P.A.!', end=' ')
else:
    print('Digite somente números e/ou o número de termos é positivo.')
  • Welcome. Next blocks of code, enter para abrir e to close the code block

  • This might help you: https://answall.com/questions/359166/formationdata-out

3 answers

3

For this, use the library textwrap who has the function wrap that receives the text and the maximum amount of characters you want per line, returning a list of strings that respect the defined size.

If you have the string relating to his P.A.:

pa = '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15'

To display it in multiple lines with a maximum size of 10, for example, just do:

from textwrap import wrap

for line in wrap(pa, width=10):
    print(line)

The exit would be:

1, 2, 3,
4, 5, 6,
7, 8, 9,
10, 11,
12, 13,
14, 15

Note that the lines will not necessarily have 10 characters in size, but all respect the size maximum 10, without breaking the contents in half.

Switching to width=30 we would have:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15

inserir a descrição da imagem aqui

Source: https://xkcd.com/353/

  • He also made fun of the kkk answer

2


I’m posting my answer as a complement to reply by @Woss. Your question specifies that you want to handle your result string to have a maximum of 100 so that your content fits on the screen. My answer approaches the problem differently, so I want to leave it here as an alternative, so that some future visitor has other options of solution to the same problem.

Instead of limiting the number of characters per line, you can limit how many terms per line you want and show them as "columns".

Code

from itertools import cycle

a1, r, ter = 1, 2, 30

# nosso "paginador"
itens_por_linha = 6
ends = [''] * (itens_por_linha - 1)
ends.append('\n')
# ends = ['', '', '', '', '', '\n']

for item, end in zip(range(a1, r * ter, r), cycle(ends)):
    print(f"{item: >5d}", end=end)

See rotating on Repl.it

Upshot

    1    3    5    7    9   11
   13   15   17   19   21   23
   25   27   29   31   33   35
   37   39   41   43   45   47
   49   51   53   55   57   59

Explanation of the code

range(start, stop, step) (#Docs)

As you yourself have already used in your code, I use the range to generate the P.A. Being:

  • a1 the parameter start;
  • r * ter will be the stop to ensure that the size of the range generated has exactly N elements defined by the variable ter;
  • r will be the step
a1, r, ter = 1, 2, 10
pa = list(range(a1, r * ter, r))

print(pa)
# [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
print(len(pa))
# 10

print(*objects, end='\n') (#Docs)

In my solution, I use the parameter end that the function print accepts to control when I must break the line.

for i in range(3):
    print(i)
# Resultado:
# 0
# 1
# 2

for i in range(3):
    print(i, end=" ")
# Resultado:
# 0 1 2

zip(*iterables) (#Docs)

The function zip is used to traverse "parallel" N. Example:

nums = [1, 2, 3]
letras = ['A', 'B', 'C']
simbolos = ['!', '@', '#', '$']

for num, letra in zip(nums, letras):
    print(f"{letra}{num}", end=', ')
# A1, B2, C3

for num, letra, simb in zip(nums, letras, simbolos):
    print(f"{letra}{num}({simb})", end=', ')
# A1(!), B2(@), C3(#)

Note that zip always stop iterating in its shortest iterable, in the example above simbolos has size 4, but iteration for after the 3rd item because nums and letras have only 3 items.

You can use the zip outside the for, for the return of zip is an eternal too. See:

nums = [1, 2, 3]
letras = ['A', 'B', 'C']
simbolos = ['!', '@', '#', '$']

lista_1 = list(zip(nums, letras))
lista_2 = list(zip(nums, letras, simbolos))


print(lista_1)
# [(1, 'A'), (2, 'B'), (3, 'C')]

print(lista_2)
# [(1, 'A', '!'), (2, 'B', '@'), (3, 'C', '#')]

itertools.cycle(iterable) (#Docs)

In my solution I use the cycle to create an infinite repetition of the characters I want to use as end of print. See a simple example:

from itertools import cycle

abc = cycle("ABC")
nums = range(1, 6)

for letra, num in zip(abc, nums):
    print(f"{letra}{num}", end=", ")
# A1, B2, C3, A4, B5, 

par_impar = ('par', 'ímpar')
nums = range(5)

lista = list(zip(nums, par_impar))
print(lista)
# [(0, 'par'), (1, 'ímpar'), (2, 'par'), (3, 'ímpar'), (4, 'par')]

String formatting

In the solution print I use formatting >5d, which means:

print(f"{item: >5d}")
#             │││└── "d": formatação para números inteiros
#             ││└─── "5": largura do resultado
#             │└──── ">": alinhamento a direita
#             └───── " ": preenchimento com espaços

Examples:

item = 123

print(f"{item: >5d}")  # "  123"
print(f"{item: <5d}")  # "123  "
print(f"{item: ^5d}")  # " 123 "
print(f"{item:_>5d}")  # "__123"
print(f"{item:0>7d}")  # "0000123"

Behold Pyformat.info and the documentation for more information.


That said, now you should understand what my code does, basically:

  • Creates the string that will be used as a separator between PA terms.

    If itens_por_linha for 4, creates an infinite iterator that generates 3 empty strings and 1 line break (['', '', '', '\n', '', '', '', '\n', '', ...]).

  • These characters are used by print to define whether the algorithm will break the line, or printara the term on the same line.

  • Traverse PA and limiter generator "parallel" using zip

  • Printa the result

0

I commented on the parts I inserted. I thought it better to break the number and not simply by the size of the line to prevent a number from being broken between lines.

texto = 'Calculadora de Progressão Aritmética'
print('=' * 100)
print(f'{texto: ^100}')
print('=' * 100)
a1 = input('Digite o primeiro termo da P.A.: ')
r = input('Digite a razão da P.A.: ')
ter = input('Quantos termos da P.A. deseja visualizar? ')
cont = 0
linha = 0  ### Nova linha de código
if a1.isdigit() and r.isdigit() and ter.isdigit() or '-' in a1 or '-' in r:
    for i in range(0, int(ter)):
        cont = cont + 1
        if True:
            an = int(a1) + (cont - 1) * int(r)
        print(f'{an}', end=', ')
        ### Novas lihas de código ###
        if linha>=100:
            print('\n')
            linha = 0
        else:
            linha += len(str(an)) + 2 # tamanho do número e mais dois dígitos do espaço e vírgula
        ##############################
    print(f'sao os {ter} primeiros termos da P.A.!', end=' ')
else:
    print('Digite somente números e/ou o número de termos é positivo.')

Another solution would be to sum up the answers in a text like resposta += f'{an}, ' and use resposta[i:100+i] within a for, but would break numbers in half.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.