Remove Newline Characters from String in Python
In Python, you can remove newline characters (such as '\n') from a string using various methods. Here are some examples:
Example 1: Using `str.replace()` Method
# Sample string with newline characters
text = "Hello\nworld\nPython\n"
# Remove newline characters using str.replace()
text_without_newlines = text.replace("\n", "")
# Print the string without newline characters
print("String without newlines:", text_without_newlines)
Output:
String without newlines: HelloWorldPython
Example 2: Using `str.strip()` Method
# Sample string with leading and trailing newline characters
text = "\nHello\nworld\nPython\n\n"
# Remove newline characters using str.strip()
text_without_newlines = text.strip("\n")
# Print the string without newline characters
print("String without newlines:", text_without_newlines)
Output:
String without newlines: HelloWorldPython