To remove newline characters (\n
) from a string in Python, you can use the replace()
method or strip()
method, depending on the use case.
- 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
- 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
- Using
splitlines()
: If you want to break the string into lines and then join them back without newlines, you can usesplitlines()
: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.