Doubt in week 5.Exercise que 1

Why we were not able to print string in the lower case?

It’s because in the for loop, you are updating the `item` variable (iterating variable) as `item.lower()` and not the actual lines list items.

1 Like

Try this:
lines = [item.lower() for item in lines]

Thanks kaustabh.

However, I tried approaching it slightly differently by two methods than the method described by pratyush sir in the lecture. I got successful in getting desired output in my first method but not in second method. Can you help me why I am getting different output in my second method?

  • Method 1. Creating a new empty list and appending it with lower case version of strings. And this seems to correctly work out.
f = open("W05_Data_poem.txt", "r")
lines = f.readlines()
print(lines)
f.close()
Z=[]
for item in lines:
    Z.append(item.lower())

print(Z)
  • Method 2. Creating a new empty list and joining the list of lowered case string with the empty list. But here i am getting an entirely different answer. don’t know why.
f = open("W05_Data_poem.txt", "r")
lines = f.readlines()
print(lines)
f.close()
Z=[]
for i in range (len(lines)):
    Z=Z+list(lines[i].lower())

print(Z)

well, lines[i] represent a string. And what you are doing is you are appending the “lowered” list() version of that string.
A string is just a sequence(list) of characters. Applying list() on a string will give you a list of those characters.

2 Likes

Exactly, @Ajay1567, you are appending a list of characters from the string to the Z list in the 2nd method

1 Like