0

My output:

I have CMShehbaz
CMShehbaz

Expected:

I have CMShehbaz CMShehbaz

I am trying get result in one line. I tried with end="", concat +, but did not work. I want result in one line.

lines = []
with open('user.txt') as f:
    lines = f.readlines()

count = 0
for line in lines:
    count += 1
    print("I have {}  {}".format(line,line) )
    print(f'line {count}: {line}')
martineau
  • 119,623
  • 25
  • 170
  • 301
Usman
  • 63
  • 2
  • 13

2 Answers2

2

I'm not quite sure why you have a counter in there if all you want is a single string, but this will do that job.

user.txt

CMShehbaz1
CMShehbaz2
CMShehbaz3

python file

with open('user.txt') as f:
    foo = "I have "
    bar = " ".join(line.strip() for line in f)
    print(foo+bar)

# Or you can do

    foo = " ".join(line.strip() for line in f)
    print(f"I have {foo}")

Gives you the output:

I have CMShehbaz1 CMShehbaz2 CMShehbaz3

If you want to know how many names are in foo then you can do

    print(len(foo.split(' ')))  # this will give you 3
SimonT
  • 974
  • 1
  • 5
  • 9
1

I suspect that "user.txt" is a list of usernames each on a new line.

so in your code line will look something like "USER\n"

You can strip off the "\n" character of use some of the solutions posted previously: How to read a file without newlines?

tgpz
  • 161
  • 10