I want to read line from standard input, like a string separated by commas, then print it the same line with additional word in one line. However, when printing it out, additional word always prints out in new line. But I need them in one line.
Here is my code
while 1:
try:
line = sys.stdin.readline()
except KeyboardInterrupt:
break
if not line:
break
additional = "END"
print(line+additional)
And when I try it:
>>python3.4 output.py
>>a, b
>>a, b
>>END
>>
But I want it:
>>python3.4 output.py
>>a, b
>>a, bEND
Your line
value contains a newline character ; strip it from the value:
print(line.rstrip('\n') + additional)
str.rstrip()
removes characters from the end; here we ask it to remove all newlines from the end of line
; it returns the a string object with those newline characters removed.
Demo:
>>> line = 'Hello, world!\n'
>>> line.rstrip('\n')
'Hello, world!'
>>> additional = 'END'
>>> print(line + additional)
Hello, world!
END
>>> print(line.rstrip('\n') + additional)
Hello, world!END
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.