Reputation: 258
I am trying to figure out why my print statement is breaking into two seperate lines rather then just printing in one line. I wrote a for loop that bascially takes in a file with Websites like this
example0.com
example1.com
example2.com
example3.com
example4.com
and starts from the 2nd line and iterates through the file.
with open('examplefile') as second_start:
next(second_start)
for line in second_start:
print('"hostNames": [{"name":' + ' "' + str(line) + '",' + '" source": "DNS"}],')
The output of this is
"hostNames": [{"name": "example1.com
"," source": "DNS"}],
"hostNames": [{"name": "example2.com
"," source": "DNS"}],
"hostNames": [{"name": "example3.com
"," source": "DNS"}],
"hostNames": [{"name": "example4.com
"," source": "DNS"}],
The output I would like is if the print statment just printed it on one line like this
"hostNames": [{"name": "example1.com"," source": "DNS"}],
"hostNames": [{"name": "example2.com"," source": "DNS"}],
"hostNames": [{"name": "example3.com"," source": "DNS"}],
"hostNames": [{"name": "example4.com"," source": "DNS"}],
Any help is greatly appreciated.
Upvotes: 1
Views: 405
Reputation: 1141
Your file is that:
example0.com
example1.com
example2.com
example3.com
example4.com
And it is equal to that:
example0.com\nexample1.com\nexample2.com\nexample3.com\nexample4.com
The \n character is a new line character. Look at that:
>>> print("Hello\nWorld")
Hello
World
So you should delete \n characters from your strings. You can do it by using str.rstrip("\n")
>>> s = "abc\n"
>>> s.rstrip("\n")
"abc"
Upvotes: 0
Reputation: 71
You can use the readlines() method , that returns a list containing each line in the file as a list item.
after that you can iterate through this list to get the values you need
with open('examplefile', 'r') as second_start:
lines_list = second_start.readlines()
for line in lines_list:
print('"hostNames": [{"name":' + ' "' + line + '",' + '" source": "DNS"}],')
Upvotes: 0
Reputation: 7897
Change
print('"hostNames": [{"name":' + ' "' + str(line) + '",' + '" source": "DNS"}],')
to
print('"hostNames": [{"name":' + ' "' + str(line).strip() + '",' + '" source": "DNS"}],')
The strip()
will remove and leading or trailing spaces, \r
, or \n
.
That being said I would recommend writing your print a little cleaner using f-strings. You need to double up any brackets to escape them though.
print(f'"hostNames": [{{"name": "{str(line).strip()}", " source": "DNS"}}],')
You can also just do .rstrip('\n')
if you only want to remove the new line at the end.
Upvotes: 3
Reputation: 568
Well, you can remove newline character from str(line)
by using str(line).rstrip("\n")
I know that you can use just .rstrip()
but specifying "\n"
will ensure that you're removing only newline character keeping other special characters untouched.
Upvotes: 1