List issue in python -


don't understand why adds empty list object end. can explain , me write proper code without empty string? thank you!

mean_temp_list = mean_temp.readline().strip() city_temp=mean_temp_list.split(",") while mean_temp_list:     mean_temp_list = mean_temp.readline().strip()     city_temp+=mean_temp_list.split(",")     print(city_temp) ['beijing', 'china', '30.9', '-8.4', 'cairo', 'egypt', '34.7', '1.2']  ['beijing', 'china', '30.9', '-8.4', 'cairo', 'egypt', '34.7', '1.2', 'london', 'uk', '23.5', '2.1']  ['beijing', 'china', '30.9', '-8.4', 'cairo', 'egypt', '34.7', '1.2', 'london', 'uk', '23.5', '2.1', 'nairobi', 'kenya', '26.3', '10.5']  ['beijing', 'china', '30.9', '-8.4', 'cairo', 'egypt', '34.7', '1.2', 'london', 'uk', '23.5', '2.1', 'nairobi', 'kenya', '26.3', '10.5', 'new york city', 'usa', '28.9', '-2.8']  ['beijing', 'china', '30.9', '-8.4', 'cairo', 'egypt', '34.7', '1.2', 'london', 'uk', '23.5', '2.1', 'nairobi', 'kenya', '26.3', '10.5', 'new york city', 'usa', '28.9', '-2.8', 'sydney', 'australia', '26.5', '8.7']  ['beijing', 'china', '30.9', '-8.4', 'cairo', 'egypt', '34.7', '1.2', 'london', 'uk', '23.5', '2.1', 'nairobi', 'kenya', '26.3', '10.5', 'new york city', 'usa', '28.9', '-2.8', 'sydney', 'australia', '26.5', '8.7', 'tokyo', 'japan', '30.8', '0.9']  ['beijing', 'china', '30.9', '-8.4', 'cairo', 'egypt', '34.7', '1.2', 'london', 'uk', '23.5', '2.1', 'nairobi', 'kenya', '26.3', '10.5', 'new york city', 'usa', '28.9', '-2.8', 'sydney', 'australia', '26.5', '8.7', 'tokyo', 'japan', '30.8', '0.9', ''] 

issue

because string splitting has trailing comma.

>>> 'a,b'.split(',') ['a', 'b'] >>> 'a,b,'.split(',') ['a', 'b', ''] #          ^ 

you should use .strip(',') remove such trailing commas:

>>> 'a,b,'.strip(',').split(',') ['a', 'b'] 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -