w3resource

Python: Remove a newline in Python


Remove newline from a string.

Write a Python program to remove a newline in Python.

Python String Exercises: Remove a newline in Python

Sample Solution:

Python Code:

# Define a variable 'str1' and assign it the value 'Python Exercises' followed by a newline character.
str1 = 'Python Exercises\n'

# Print the value of 'str1', which includes a newline character, resulting in a new line in the output.
print(str1)

# Use the rstrip() method to remove trailing whitespace characters, including the newline character.
# Then, print the modified 'str1' with trailing whitespace removed.
print(str1.rstrip()) 

Sample Output:

Python Exercises                                                                                              
                                                                                                              
Python Exercises 

For more Practice: Solve these Related Problems:

  • Write a Python program to remove newline characters from a multi-line string using the replace() method.
  • Write a Python program to split a string into lines and then join them into a single line without newline characters.
  • Write a Python program to use regular expressions to eliminate newline characters from the given text.
  • Write a Python program to use splitlines() and join() to output a string with all newline characters removed.

Python Code Editor:

Previous: Write a Python program to sort a string lexicographically.
Next: Write a Python program to check whether a string starts with specified characters.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.