How to Remove a Trailing Newline

How to remove newline and trailing space from a list

Using strip() and replace() in a list comprehension. I've called your list li as list is a built-in function of python.

li = ['Path', 'Metric Group', 'Metric Type', 'Tue\n23rd', 'Wed\n24th', 'Thu\n25th', '','Week\n23']    
print([e.strip().replace('\n', '') for e in li if e != ''])

# prints:
['Path', 'Metric Group', 'Metric Type', 'Tue23rd', 'Wed24th', 'Thu25th', 'Week23']

Note: strip() will remove all leading and trailing whitespace. If you only want to remove trailing whitespace then use rstrip().

Remove newline at the end of a file in python

use str.rstrip() method:

my_file =  open("text.txt", "r+")
content = my_file.read()
content = content.rstrip('\n')
my_file.seek(0)

my_file.write(content)
my_file.truncate()
my_file.close()

Remove trailing newline character using fgets

If you are using strtok, then you can use " \n" as the delimiter and the newline will be taken care of.

int main() {

char line1[100];
fgets(line1, 100, stdin);
printf("%s", line1);

const char *delim = " \n";

char *token;
token = strtok(line1, delim);

while(token != NULL){
printf("%s\n", token);
palindrome(token);

token = strtok(NULL, delim);
}

...

}

Another great method to remove the newline is to use strcspn like this:

char line[1024];
fgets(line, sizeof line, stdin);

line[strcspn(line, "\n")] = 0; // removing newline if one is found

Remove single trailing newline from String without cloning

You can use String::pop or String::truncate:

fn main() {
let mut s = "hello\n".to_string();
s.pop();
assert_eq!("hello", &s);

let mut s = "hello\n".to_string();
let len = s.len();
s.truncate(len - 1);
assert_eq!("hello", &s);
}

jinja2 how to remove trailing newline

Change your loop to strip whitespace from the top AND bottom of the output (notice extra - at the for loop close):

{% for key, value in querystring.items() -%}
{{ key }}: '{{ value }}'
{%- endfor %}

In my tests (using https://github.com/abourguignon/jinja2-live-parser), the - must come after the first {%, not before the last to achieve what you're asking for.

How to remove newline from the end of a file using Perl

You can try this:

perl -pe 'chomp if eof' file.txt

Here is another simple way, if you need it in a script:

open $fh, "file.txt"; 
@lines=<$fh>; # read all lines and store in array
close $fh;
chomp $lines[-1]; # remove newline from last line
print @lines;

Or something like this (in script), as suggested by jnhc for the command line:

open $fh, "file.txt"; 
while (<$fh>) {
chomp if eof $fh;
print;
}
close $fh;


Related Topics



Leave a reply



Submit