[Tutor] Problem with code interating thri a list
Chris Clifton
chris9361 at yahoo.com
Tue Aug 2 10:59:18 EDT 2016
Hello Everyone,
I have been practicing with strings. Splitting them, joining them, changing case. All has been going well but came across a exercise in one of the code practice sites that has you changing the case of different characters in a string. Anything in upper case is converted to lower case and anything in lower case is converted to upper. The solution I have created seems to work but I have not been able to figure out how to join the string back together. String I'm using is "This Is A Test!" to be changed to "tHIS iS a tEST!".
My Logic: Since a string is immutable, I converted it to a list to separate out the characters and keep them in order. Idea is to change the case of the characters in the list then run a join to convert it back to a string.
Can you point me in the right direction?
the print statements in the code are for my debugging and will be removed in the end.
Python 3.5.1 on Windows 10.---------------------------------------------------------------------
# Create a function that will take a string and change the upper case characters to lower
# and the lower case characters to upper.
# Create a function.
def convert(text):
print(text)
text = list(text)
# Convert string to a list to separate/split characters and maintain order.
print(text)
# Check case and convert to opposite case.
for item in text:
if item == item.lower():
item = item.upper()
print(item)
else:
item = item.lower()
print(item)
# Convert list back into string with .join.
result = "".join(text)
print()
print(result)
return result
# Call the function
print(convert("This Is A Test!"))
-----------------------------------------------------------------------------
Thanks,Chris Clifton
More information about the Tutor
mailing list