Friday, January 24, 2025
HomeProgrammingRemoving newline character from string in Python

Removing newline character from string in Python

To remove newline characters (\n) from a string in Python, you can use the replace() method or strip() method, depending on the use case.

  1. Using replace(): This removes all newline characters within the string.
    my_string = "Hello\nWorld\n"
    my_string = my_string.replace("\n", "")
    print(my_string)
    

    This will output:

    HelloWorld
    
  2. Using strip(): This removes newline characters from the beginning and end of the string (but not from the middle).
    my_string = "\nHello World\n"
    my_string = my_string.strip()
    print(my_string)
    

    This will output:

    Hello World
    
  3. Using splitlines(): If you want to break the string into lines and then join them back without newlines, you can use splitlines():
    my_string = "Hello\nWorld\n"
    my_string = "".join(my_string.splitlines())
    print(my_string)
    

    This will output:

    HelloWorld
    

Which method you choose depends on whether you want to remove all newline characters or just those at the edges.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x