简体   繁体   中英

Breaking Python dict output onto new line after certain length

I am trying to find a way to print the values in a dict so that after a certain length (5 for example) the set breaks and continues on a new lines.

Example:

dict = {'Upper':'ABCDEFGHI', 'Lower':'abcdefghi', 'Number':'123456789'}

def insertNewlines(text, lineLength):
    if len(text) <= lineLength:
        return text
    else:
        return text[:lineLength] + '\n' + insertNewlines(text[lineLength:], lineLength)

for key, val in dict.items():
    print(insertNewlines(val,5))

Output

ABCDE
FGHI
abcde
fghi
12345
6789

Desired Output:

ABCDE
abcde
12345

FGHI
fghi
6789

Assuming all dict values have the same length the following code would give the desired output by taking string slices at increasing intervals.

dict = {'Upper':'ABCDEFGHI', 'Lower':'abcdefghi', 'Number':'123456789'}

line_length = 5
value_length = len(next(iter(dict.values())))

count = 0
while count * line_length < value_length:
    for value in dict.values():
        print(value[count * line_length: (count + 1) * line_length])
    print()
    count += 1

Or similarly, using a for loop over a range

import math
for i in range(math.ceil(value_length / line_length)):
    for value in dict.values():
        print(value[i * line_length: (i + 1) * line_length])
    print()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM