Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

manipulating list items python

Tags:

python

string

line = "english: while  french: pendant que  spanish: mientras  german: whrend "

words = line.split('\t')

for each in words:
 each = each.rstrip()

print words

the string in 'line' is tab delimited but also features a single white space character after each translated word, so while split returns the list I'm after, each word annoyingly has a whitespace character at the end of the string.

in the loop I'm trying to go through the list and remove any trailing whitespaces in the strings but it doest seem to work, suggestions?

like image 518
dave Avatar asked Apr 17 '26 05:04

dave


1 Answers

Just line.split() could give you stripped words list.

Updating each inside the loop does not make any changes to the words list

Should be done like this

for i in range(len(words)):
    words[i]=words[i].rstrip()

Or

words=map(str.rstrip,words)

See the map docs for details on map.

Or one liner with list comprehension

words=[x.rstrip() for x in line.split("\t")]

Or with regex .findall

words=re.findall("[^\t]+",line)
like image 63
YOU Avatar answered Apr 19 '26 18:04

YOU



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!