4

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
reiallenramos
  • 1,235
  • 2
  • 21
  • 29

2 Answers2

4

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))
idjaw
  • 25,487
  • 7
  • 64
  • 83
  • thank you! I just started learning python and I'm still familiarizing myself with the functions. cheers – reiallenramos Jun 24 '17 at 02:06
  • 1
    Just keep in mind that ``strip()`` with no arguments removes all whitespace and from both start and end of the string. Use ``rstrip()`` if only want whitespace removed from the end of the string, and use ``rstrip('\n')`` if only wan't to remove the new line character. – Graham Dumpleton Jun 24 '17 at 02:06
1

You can replace your concatString to be something like that :

def concatString(string1, string2):
    return (string1 + string2).replace('\n','')
SEDaradji
  • 1,348
  • 15
  • 18