Home > Back-end >  Python if "-" in "sentence" -> \n
Python if "-" in "sentence" -> \n

Time:03-13

I have a quote generator and whenever I run the script, the variable "sentence" is set to the quote. I would like that when an author is specified (always with "- Author"), a blank line is set in front of it (\n). Some citations have no author attribution, no "- Author". So how can I always put a "\n" in front of a "-" in sentence?

CodePudding user response:

You could use the built-in replace() method like this:

quote = "The quote - Author"
new_quote = quote.replace("-", "\n-")
print(new_quote)

Output:

The quote
- Author

Here is the official documentation for the replace method.

CodePudding user response:

A simple solution would be to replace the (-) with the same char but a newline character(\n) before it.

You can do it like this :

sentence  = ("Random generated quote - A Magotra")

print(sentence.replace("-", "\n-")) 

Output -

Random generated quote 
- A Magotra

CodePudding user response:

A quick and dirty solution would be

sentence.replace("-", "\n-")

but it's worth noting this will trigger a new line anywhere a dash appears in the variable.

  • Related