Member Avatar for gianniszaf

Hi there,

I have the following string which is tab seperated

dasj    dhsahdwe	dhasdhajks	ewqhehwq	dsajkdhas
edward das	dsaw	das	daswf
fjdk    ewf	jken	dsajkw	dskdw
hklt    ewq	vn1	daskcn	daskw

How can I format it in python in order to make each column to have the width of the longest cell in this column? And look like below

dasj       dhsahdwe   dhasdhajks ewqhehwq   dsajkdhas 
edward    das        dsaw       das        daswf     
fjdk       ewf        jken       dsajkw     dskdw     
hklt       ewq        vn1        daskcn     daskw

Thanks a lot.

One way to do this is to pad each word with spaces at the end to make the words equal in length (max length + 2):

s = """\
dasj    dhsahdwe	dhasdhajks	ewqhehwq	dsajkdhas
edward das	dsaw	das	daswf
fjdk    ewf	jken	dsajkw	dskdw
hklt    ewq	vn1	daskcn	daskw
"""

# create a word list
mylist = s.split()
#print mylist

# find maximum word length
length = 0
for w in mylist:
    size = len(w)
    if size > length:
        length = size

#print length

# pad spaces to the end of each word
# add a newline to every fifth word
newlist = []
# max length + 2 spaces
pad = length + 2
ix = 1
for w in mylist:
    size = len(w)
    # pad with spaces
    w = w + ' '*(pad - size)
    if ix % 5 == 0:
        # add a newline
        w = w + '\n'
    newlist.append(w)
    ix += 1

#print newlist

# now show the words in the new list
for w in newlist:
    print w,

"""
my display -->
dasj         dhsahdwe     dhasdhajks   ewqhehwq     dsajkdhas
edward       das          dsaw         das          daswf
fjdk         ewf          jken         dsajkw       dskdw
hklt         ewq          vn1          daskcn       daskw
"""

I used space padding, because tabs are set differently depending on the editor you want to display with.

This might be a little simpler ...

data = """\
dasj    dhsahdwe	dhasdhajks	ewqhehwq	dsajkdhas
edward das	dsaw	das	daswf
fjdk    ewf	jken	dsajkw	dskdw
hklt    ewq	vn1	daskcn	daskw
"""

# find the length of the longest word and add 2
length = max(len(w) for w in data.split()) + 2

new_data = ""
for line in data.split('\n'):
    for word in line.split():
        new_data += word.ljust(length)
    new_data += '\n'
    
# test it ...
print new_data

Python has functions for string justification.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.