0

how to keep the space betwen the words? in the code it deletes them and prints them in column.. so how to print them in row and with the space?

s ='[]'
f = open('q4.txt', "r")
for line in f:
    for word in line:
        b = word.strip()
        c = list(b)
        for j in b:
            if ord(j) == 32:
                print ord(33)
            if ord(j) == 97:
                print ord(123)
            if ord(j) == 65:
                print ord(91)
            chr_nums = chr(ord(j) - 1)
            print chr_nums

    f.close()
lxop
  • 7,596
  • 3
  • 27
  • 42
  • Take a look at this answer https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space – maQ Dec 06 '18 at 10:18

2 Answers2

0

Short answer: remove the word.strip() command - that's deleting the space. Then put a comma after the print operation to prevent a newline: print chr_nums,

There are several problems with your code aside from what you ask about here:

  • ord() takes a string (character) not an int, so ord(33) will fail.
  • for word in line: will be iterating over characters, not words, so word will be a single character and for j in b is unnecessary.
lxop
  • 7,596
  • 3
  • 27
  • 42
0

Take a look at the first for loop :

for line in f:

here the variable named 'line' is actually a line from the text file you are reading. So this 'line' variable is actually a string. Now take a look at the second for loop :

for word in line:

Here you are using a for loop on a string variable named as 'line' which we have got from the previous loop. So in the variable named 'word' you are not going to get a word, but single characters one by one. Let me demonstrate this using a simple example :

for word in "how are you?":
    print(word)

The output of this code will be as follows :

h
o
w

a
r
e

y
o
u
?

You are getting individual characters from the line and so you don't need to use another for loop like you did 'for j in b:'. I hope this helped you.

arunken
  • 415
  • 3
  • 15