This is a code I wrote and it works as expected. However, I think conditional statements and loops can be simplified and become more pythonic codes using methods such as list comprehension.
def erase(sts1, sts2):
erase_lst = []
for _, letter1 in enumerate(sts1.upper()):
if letter1.isalpha():
if letter1 not in erase_lst:
erase_lst.append(letter1.upper())
erase_lst.append(chr(ord(letter1.upper()) + 32))
sts = ''
for letter2 in sts2:
letter2 = ' ' if letter2 in erase_lst else letter2
sts += letter2
return sts
Question: For the first part, the successive for loop and if statements with 3 indentations can be organized in a better way?
This is what I tried for the second part, but an error occurred in the bold line.
sts = '' ' ' **if letter2 in erase_lst else letter2 for letter2 in sts2** sts += letter2 return sts
According to the pycharm, ‘letter2’ is an unresolved reference and the end of the statement is expected.
l = [1,2,3,4,5] print(**[x+1 if x >= 5 else x+5 for x in l]**)
However, this simple code has the same structure as the above bold line (at least I cannot get the difference) and works without any problem.
Question: Could you explain what I did wrong here?
Won is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.