Skip to content

Instantly share code, notes, and snippets.

@jacqueswww
Created September 25, 2017 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacqueswww/6c424c8b52358fbae4831660ba9b7541 to your computer and use it in GitHub Desktop.
Save jacqueswww/6c424c8b52358fbae4831660ba9b7541 to your computer and use it in GitHub Desktop.
Replace newlines in a string, but allow x newlines to remain at the beginning.
def remove_extra_newlines(input_str, newlines_left=3):
number_of_newlines = input_str.count('\n')
if number_of_newlines > newlines_left:
amount_to_strip = number_of_newlines - newlines_left
return input_str[::-1].replace('\n', ' ', amount_to_strip)[::-1]
else:
return input_str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment