Convert list to lower-case

Here is how it can be done:

In [6]: l = ['Suzuki music', 'Chinese music', 'Conservatory', 'Blue grass']

In [7]: map(str.lower, l)
Out[7]: ['suzuki music', 'chinese music', 'conservatory', 'blue grass']

One of the reasons your code doesn't behave as expected is that item.lower() doesn't modify the string (in Python, strings are immutable). Instead, it returns the lowercase version of the string, which your code then disregards.


You can use method str.lower().


Easiest might be a list comprehension:

with open('./input.txt', 'r') as f:
    results = [ line.strip().lower() for line in f if line]

... I'm assuming you're willing to strip all leading and trailing whitespace from each line; though you could use just .rstrip() or even .rstrip('\n') to be more specific in that. (One would preserve any whitespace on the left of each line, and the other would strip only the newlines from the ends of the lines.

Also this will filter out any blank lines, including the terminal empty line which is almost always found at the end of a text file. (This code will work even with the rare text file that doesn't end with a newline).


Instead of

for item in list:
    item.lower()

change the name of the variable list to l or whatever you like that isn't a reserved word in Python and use the following line, obviously substituting whatever you name the list for l.

l = [item.lower() for item in l]

The lower method returns a copy of the string in all lowercase letters. Once a string has been created, nothing can modify its contents, so you need to create a new string with what you want in it.

Tags:

Python