Hello guys,

just joined the community. Found it through google. :)

I am basically new to python, only couple of days of knowledge. I am trying to
make all the words in a txt file appear in 4 or 5 in a row.

so the txt file looks like this:

!algiers!
!atlanta!
!baghdad!
!bangkok!
!beijing!
!bogota!
!buenos aires!
!cairo!
!chennai!
!chicago!
!delhi!
!essen!
!ho chi mihn ci
!hong kong!
!istanbul!
!jakarta!
!johannesburg!

and the out put should be:

!algiers! !atlanta! !baghdad! !bangkok!
!beijing! !bogota! !buenos aires! !cairo!

This is the code I used so far

f = file('cities.txt','r')

while True:
    line = f.readline()
    if len(line) == 0:
       break
    x= line.strip()
    x= '!'+x+'!'
    x= x[0:15]
    x= x.rjust(15)
    print x

I used .split but not getting the same result. I dont know what to do now.

Quoted to include [code] tags.

Hello guys,

just joined the community. Found it through google. :)

I am basically new to python, only couple of days of knowledge. I am trying to
make all the words in a txt file appear in 4 or 5 in a row.

so the txt file looks like this:

!algiers!
!atlanta!
!baghdad!
!bangkok!
!beijing!
!bogota!
!buenos aires!
!cairo!
!chennai!
!chicago!
!delhi!
!essen!
!ho chi mihn ci
!hong kong!
!istanbul!
!jakarta!
!johannesburg!

and the out put should be:

!algiers! !atlanta! !baghdad! !bangkok!
!beijing! !bogota! !buenos aires! !cairo!

This is the code I used so far

f = file('cities.txt','r')

while True:
    line = f.readline()
    if len(line) == 0:
       break
    x= line.strip()
    x= '!'+x+'!'
    x= x[0:15]
    x= x.rjust(15)
    print x

Use a counter (code is not tested but for illustration only).

f = file('cities.txt','r')

print_max=5
ctr=0
for line in f:
    x = line.strip()
#    x= '!'+x+'!'
#    x= x[0:15]
#    x= x.rjust(15)
    print x,     ## note the comma
    ctr += 1
    if ctr >= print_max:
        print
        ctr = 0
print     ## newline for final print

Thanks a lot woooee. I have one question regarding counter, is print_max is for the max counter limit ? I was trying for loops and I was getting wrong answers I guess.

Quoted to include [code] tags.

f = file('cities.txt','r')

while True:
    line = f.readline()
    if len(line) == 0:
       break
    x= line.strip()
    x= '!'+x+'!'
    x= x[0:15]
    x= x.rjust(15)
    print x

Use a counter.

f = file('cities.txt','r')

print_max=5
ctr=0
while True:
    line = f.readline()
    x = line.strip()
    if len(x) == 0:
       break
#    x= '!'+x+'!'
#    x= x[0:15]
#    x= x.rjust(15)
    print x,     ## note the comma
    ctr += 1
    if ctr >= max:
        print
        ctr = 0
print     ## newline for final print

print_max is the maximum number to print on one line. A variable is used so it can be any number input.

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.