reiallenramos
reiallenramos

Reputation: 1295

Python how to remove newline from sys.stdin.readline()

I'm defining a function that concatenates two strings given by the user, but the string returned by sys.stdin.readline() includes the newline character so my output doesn't look concatenated at all (technically, this output is still concatenated, but with a "\n" between the two strings.) How do I get rid of the newline?

def concatString(string1, string2):
    return (string1 + string2)

str_1 = sys.stdin.readline()
str_2 = sys.stdin.readline()
print( "%s" % concatString(str_1, str_2))

console:

hello
world
hello
world

I tried read(n) that takes in n number of characters, but it still appends the "\n"

str_1 = sys.stdin.read(5) '''accepts "hello" '''
str_2 = sys.stdin.read(3) '''accepts "\n" and "wo", discards "rld" '''

console:

hello
world
hello
wo

Upvotes: 5

Views: 14943

Answers (2)

idjaw
idjaw

Reputation: 26600

Just call strip on each string you take from input to remove surrounding characters. Make sure you read the documentation linked to ensure what kind of strip you want to perform on the string.

print("%s" % concatString(str_1.strip(), str_2.strip()))

Fixing that line and running your code:

chicken
beef
chickenbeef

However, based on the fact that you are taking a user input, you should probably take the more idiomatic approach here and just use the commonly used input. Using this also does not require you to do any manipulation to strip unwanted characters. Here is the tutorial for it to help guide you: https://docs.python.org/3/tutorial/inputoutput.html

Then you can just do:

str_1 = input()
str_2 = input()

print("%s" % concatString(str_1, str_2))

Upvotes: 4

user7870824
user7870824

Reputation:

You can replace your concatString to be something like that :

def concatString(string1, string2):
    return (string1 + string2).replace('\n','')

Upvotes: 1

Related Questions