-1

If I have a speech, for example, that is being inputted by the user:

speech = input("Enter your speech: ")

and if this input is (for example):

Hello, welcome to my speech.
This is my exemplar speech.
Which I am trying to analyze.

But if I were to print(speech), I'd get an output of:

"Hello, welcome to my speech."

but not the other 2 lines. How can I recognize the linefeed (\n) and replace it as a space, so my output will be:

"Hello, welcome to my speech. This is my exemplar speech. Which I am trying to analyze."
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
13K
  • 19
  • 2
  • 2
    input only returns one line. If you want more than one you need to make a loop and decide when to stop. – Random832 Nov 17 '15 at 02:58
  • 3
    You don't see the line feed at all. You only received one line. You might just try slurping with `sys.stdin.read()`, though this requires the user to hit `Ctrl-D` (or IIRC in Windows, `Ctrl-Z` followed by `Enter`) when they're done entering lines. – ShadowRanger Nov 17 '15 at 02:58

1 Answers1

0

From your question's title it sounds like you're going to have the user literally enter the characters \n — which are usually called newlines, not linefeeds, by-the-way — but not on multiple lines as shown in the body of your question.

If that's the case. and they literally entered the following, all on one line, before pressing Enter:

Hello, welcome to my speech.\nThis is my exemplar speech.\nWhich I am trying to analyze.

Then you could replace all the literal '\n' substrings in it with spaces by using the string replace() method like this:

speech = input('Enter your speech: ').replace('\\n', ' ')
martineau
  • 119,623
  • 25
  • 170
  • 301
  • My appologies, I meant if a text is copy + pasted where the user is asked to input a speech... Is there any way to fix that situation? – 13K Nov 17 '15 at 16:57
  • In that case I think something like the second solution shown in [this answer](http://stackoverflow.com/questions/15692149/taking-multiline-input-with-sys-stdin/15692920#15692920) to another question might work (and would replace your call to `input()`, which also reads lines from `sys.stdin`). – martineau Nov 17 '15 at 17:21
  • What operating system are you on? If you can read individual characters as they're typed (instead of only whole lines), it would be possible, but the user would have type something special to indicate the end of the input (since pressing the Enter key doesn't indicate that anymore). – martineau Nov 17 '15 at 17:26
  • Im on Mac OS X, the problem is when I copy and paste text into the shell after running my code. It doesn't recognize '\n' but in a non-run shell, it does recognize it and works properly. – 13K Nov 18 '15 at 01:45
  • Sorry, I don't understand what "doesn't recognize '\n'" nor what pasting "in a non-run shell" means. Also, what's not working, the code in your question, the code in my answer, or the code in the linked answer? – martineau Nov 18 '15 at 22:58