Search code examples
pythonstringstdinreadline

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

Solution

  • 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))