Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How remove \n from lines

Tags:

parsing

go

line

file, _ := os.Open("x.txt")     f := bufio.NewReader(file)      for {         read_line, _ := ReadString('\n')         fmt.Print(read_line)           // other code what work with parsed line...         } 

end it add \n on every line , end program to work , only work with last line...

Please put example, i try anything end any solution what i find here not work for me.

like image 982
tseries Avatar asked Jun 09 '17 02:06

tseries


People also ask

How do you remove \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.

Does Strip remove newline Python?

Use the strip() Function to Remove a Newline Character From the String in Python. The 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.


2 Answers

You can slice off the last character:

read_line = read_line[:len(read_line)-1] 

Perhaps a better approach is to use the strings library:

read_line = strings.TrimSuffix(read_line, "\n") 
like image 115
Alex Lew Avatar answered Oct 06 '22 11:10

Alex Lew


If you want to read a file line-by-line, using bufio.Scanner will be easier. Scanner won't includes endline (\n or \r\n) into the line.

file, err := os.Open("yourfile.txt") if err != nil {     //handle error     return } defer file.Close()  s := bufio.NewScanner(file) for s.Scan() {     read_line := s.Text()      // other code what work with parsed line... } 

If you want to remove endline, I suggest you to use TrimRightFunc, i.e.

read_line = strings.TrimRightFunc(read_line, func(c rune) bool {     //In windows newline is \r\n     return c == '\r' || c == '\n' }) 

Update:
As pointed by @GwynethLlewelyn, using TrimRight will be simpler (cleaner), i.e.

 read_line = strings.TrimRight(read_line, "\r\n") 

Internally, TrimRight function call TrimRightFunc, and will remove the character if it match any character given as the second argument of TrimRight.

like image 34
putu Avatar answered Oct 06 '22 11:10

putu