I was shocked when the following code did not do what I expected it to do:
lines_list = ['this is line 1\n', 'this is line 2\n', 'this is line 3\n']
for line in lines_list:
line = line.strip()
In Perl or in Java, my usage works well. Python is the one with the unique behavior.
In Java this will work:
String[] lines = {"this is line 1\n", "this is line 2\n", "this is line 3\n"};
for (String line : lines) {
line = line.trim();
}
In Perl this will work:
my @lines = ("this is line 1\n", "this is line 2\n", "this is line 3\n");
foreach my $line (@lines) {
$line =~ s/\s+$//;
$line =~ s/^\s+//;
}
I of course expected each item in the list to become "stripped"
, i.e. in this case, to be free of the trailing '\n'
char, but it did not...
print lines_list
The output:
['this is line 1\n', 'this is line 2\n', 'this is line 3\n']
Is there an elegant way to change the list items during the for
loop? I don't want to duplicate the list...