This is my file.txt: Egg and Bacon;
Egg, sausage and Bacon
Egg and Spam;
Spam Egg Sausage and Spam;
Egg, Bacon and Spam;
I wanna convert the newLine '\n' to ' $ '. I just used: f = open(fileName)
text = f.read()
text = text.replace('\n',' $ ')
print(text)
This is my output: $ Spam Egg Sausage and Spam;
and my output must be like: Egg and Bacon; $ Egg, sausage and Bacon $ Egg ...
What am I doing wrong? I'm using #-*- encoding: utf-8 -*- Thank you.
asked Mar 25, 2015 at 9:04 4 It is possible that your newlines are represented as \r\n . In order to replace them you should do: text.replace('\r\n', ' $ ')
For a portable solution that works on both UNIX-like systems (which uses \n ) and Windows (which uses \r\n ), you can substitute the text using a regex: >>> import re
>>> re.sub('\r?\n', ' $ ', 'a\r\nb\r\nc')
'a $ b $ c'
>>> re.sub('\r?\n', ' $ ', 'a\nb\nc')
'a $ b $ c'
answered Mar 25, 2015 at 9:14 enrico.bacisenrico.bacis 29.3k10 gold badges85 silver badges114 bronze badges 2 You can use splitlines. lines = """Egg and Bacon;
Egg, sausage and Bacon
Egg and Spam;
Spam Egg Sausage and Spam;
Egg, Bacon and Spam;"""
print(" $ ".join(lines.splitlines()))
Egg and Bacon; $ Egg, sausage and Bacon $ Egg and Spam; $ Spam Egg Sausage and Spam; $ Egg, Bacon and Spam;
Or simply use rstrip and join on the file object without reading all into memory: with open("in.txt") as f:
print(" $ ".join(line.rstrip() for line in f))
Egg and Bacon; $ Egg, sausage and Bacon $ Egg and Spam; $ Spam Egg Sausage and Spam; $ Egg, Bacon and Spam;
Which is a much more efficient solution than reading all the file into memory and using a regex. You should also always use with to open your files as it closes them automatically. rstrip will remove \n
\r\n etc.. In [41]: s = "foo\r\n"
In [42]: s.rstrip()
Out[42]: 'foo'
In [43]: s = "foo\n"
In [44]: s.rstrip()
Out[44]: 'foo'
answered Mar 25, 2015 at 9:48 text = text.replace('\\n', '')
answered Oct 9, 2020 at 15:19 1 - HowTo
- Python How-To's
- Remove Newline From String in Python
Created: May-09, 2021
- Use the
strip() Function to Remove a Newline Character From the String in Python - Use the
replace()
Function to Remove a Newline Character From the String in Python - Use the
re.sub() Function to Remove a Newline Character From the String in Python
Strings in Python can be defined as the cluster of Unicode characters enclosed in single or double quotes. Like other popular
programming languages, Python also has a newline character indicated by \n . It is essentially used to trace the culmination of a line and the emergence of a new line in a string. Newline characters can also be used in f-strings. Moreover, according to the Python documentation, print statements add a newline character at the end of a string by default. This tutorial will discuss different methods to remove a newline character from a string in Python. Use the strip() Function to Remove a Newline Character From the String in PythonThe strip() function is used to remove both trailing and leading newlines from the string that it is being operated on. It also removes the whitespaces on both sides of the string. The following code uses the strip() function to remove a newline character from a string in Python. str1 = "\n Starbucks has the best coffee \n"
newstr = str1.strip()
print(newstr)
Output:
Starbucks has the best coffee
The
rstrip() function can be used instead of the strip function if there is only the need to remove trailing newline characters. The leading newline characters are not affected by this function and remain as they are. The following code uses the rstrip() function to remove a newline character from a string in Python. str1 = "\n Starbucks has the best coffee \n"
newstr = str1.rstrip()
print(newstr)
Output:
Starbucks has the best coffee
Use the replace() Function to Remove a Newline Character
From the String in PythonAlso known as the brute force method, It uses the for loop and replace() function. We look for the newline character \n as a string inside a string, and manually replace that from each string with the help of the for loop. We use a List of strings and implement this method on it. Lists are one of the four built-in datatypes
provided in Python and can be utilized to stock multiple items in a single variable. The following code uses the replace() function to remove a newline character from a string in Python. list1 = ["Starbucks\n", "has the \nbest", "coffee\n\n "]
rez = []
for x in list1:
rez.append(x.replace("\n", ""))
print("New list : " + str(rez))
Output: New list : ['Starbucks', 'has the best', 'coffee ']
Use the re.sub() Function to Remove a Newline Character From the String in PythonThe re module needs to import to the python code to use the re.sub() function The
re module is a built-in module in Python, which deals with regular expression. It helps in performing the task of searching for a pattern in a given particular string. The re.sub() function is essentially used to take a substring and replace its occurrence in the string with another substring. The following code uses the re.sub() function to remove a newline character from a string in Python. #import the regex library
import re
list1 = ["Starbucks\n", "has the \nbest", "coffee\n\n "]
rez = []
for sub in list1:
rez.append(sub.replace("\n", ""))
print("New List : " + str(rez))
Output: New List : ['Starbucks', 'has the best', 'coffee ']
Related Article - Python StringRemove Commas From String in PythonCheck a String Is
Empty in a Pythonic WayConvert a String to Variable Name in PythonRemove Whitespace From a String in Python
How do you get rid of N in Python?
Method 2: Use the strip() Function to Remove a Newline Character From the String in Python. The strip() method in-built function of Python is used to remove all the leading and trailing spaces from a string. Our task can be performed using strip function() in which we check for “\n” as a string in a string.
How do you replace n with null in Python?
An additional comment: I would recommend doing first text = text. replace('\r\n','\n') and then doing text = text. replace('\n', ' $ ') . ... . Yes, I agree that your regex solution is better. Got already my upvote, though. – juhist..
What does '\ n do in Python?
The new line character in Python is \n . It is used to indicate the end of a line of text.
How do you replace a value in Python?
Syntax of replace(). old – old substring you want to replace.. new – new substring which would replace the old substring.. count – (Optional ) the number of times you want to replace the old substring with the new substring..
|