Python Forum

Full Version: print function output wrong with strings.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi Team,
I am beginner in Python and below is my code. I want to print some content in specific format with below code but it is not printed as mention. it will be helpful if someone help to resolve it.

f = open(r"C:\Users\emanpos\bbuser.txt","r")
for x in f:
print("<Number>")
print("      %s%s%s" %("<Number>", x,"</Number>"))
print('</Number>')
Expected Output:
Output:
<Number> <Number>abc</Number> </Number>
But Output comes as below.
Output:
<Number> <Number>abc </Number> </Number>
You iterate over lines in file. What makes line a line? Newline at the end (\n)!

It also advisable to open files using with and use f-strings.
As mention use f-string and with open().
Then it look like this.
with open(r"num.txt", "r") as f:
    print("<Number>")
    for line in f:
        print(f'{" ":<4}<Number>{line.strip()}</Number>')
    print('</Number>'
Output:
<Number> <Number>1</Number> <Number>2</Number> <Number>3</Number> <Number>4</Number> <Number>5</Number> </Number>
Indentation in Python does the job of {} in C. It is how you block code.

When I try to run your program I get an error.
f = open(r"C:\Users\emanpos\bbuser.txt","r")
for x in f:
print("<Number>")
print("      %s%s%s" %("<Number>", x,"</Number>"))
print('</Number>')
Error:
File "..., line 3 print("<Number>") ^ IndentationError: expected an indented block
I don't know why you aren't getting the same error. But as snippsat says, your program is not going to work the way you want because your code blocks are not properly indented
f = open(r"C:\Users\emanpos\bbuser.txt","r")
for x in f:
    print("<Number>")
    print("      %s%s%s" %("<Number>", x,"</Number>"))
    print('</Number>')
I don't care if you use f'strings or a context manager.
for example

test.txt content

1
2
3
4
5
6
7

if you want it in lines between <Number> and </Number>

f = open("test.txt", "r").read().splitlines()
for x in f:
    print(f"<Number>{x}</Number>")
Output:
<Number>1</Number> <Number>2</Number> <Number>3</Number> <Number>4</Number> <Number>5</Number> <Number>6</Number> <Number>7</Number>
Hi,

(Of course you need proper indentation, and f strings are easier)
But if I take your original code and run it in IDLE, (and replace the file with a list of numbers)
it outputs exactly what you would like it to do.

So I suppose the file contains a CRLF on each line, that you should strip first.
Paul