My problem here is that i am trying to flip the letter cases for example:
Experiment = "ChocoLate"
if str.isupper(Experiment):
print(str.lower(Experiment))
elif str.islower(Experiment):
print(str.upper(Experiment))
The output should be something like "cHOCOlATE".
what am i doing wrong?
str.lower(Experiment)
and str.upper(Experiment)
will check if entire string Experiment
is in lower case or upper case respectively and both will result in False
as Experiment
string is neither in completely uppercase not completely lowercase.
You should check for individual characters in the string instead for lower or upper case by looping through them.
Best you can use is Python's swapcase()
function to swap case of each letter in a string.
The following should help:
experiment = "ChocoLate"
experiment_flipped = ""
for i in experiment:
# print(i)
if str.isupper(i):
# print(str.lower(i))
experiment_flipped += str.lower(i)
elif str.islower(i):
# print(str.upper(i))
experiment_flipped += str.upper(i)
print(experiment_flipped)
Here is a solution;
string = "ChocoLate"
result = ''.join([i.lower() if i != i.lower() else i.upper() for i in string ])
print(result)
OUTPUT:
cHOCOlATE
So what i did here is i simply iterated over the string ( for i in string
), converted the characters to lowercase if they are in uppercase ( i.lower() if i.= i.lower()
) else converted to uppercase ( else i.upper()
) and then joined the resulting list with no seperator ( ''.join()
)
In your case, you are checking if the entire string is in uppercase or lowercase. so str.isupper(Experiment)
and str.islower(Experiment)
both will evaluate to False
. Thats the reason you program is not printing anything. So, you either can use Python's swapcase function or you can iterate through an individual characters in the string, check its case and print the opposite case.
Experiment = "ChocoLate"
print(Experiment.swapcase())
Output:
cHOCOlATE
Experiment = "ChocoLate"
for s in Experiment:
if s.isupper():
print(s.lower(), end = '')
else:
print(s.upper(), end = '')
One way will be to solve it character by character, either by using a loop or a list comprehension.
experiment = "ChocoLate"
output = ""
for charc in list(experiment):
print(charc)
output += charc.lower() if charc.isupper() else charc.upper()
print(output)
experiment = "ChocoLate"
output = ''.join([x.lower() if x.isupper() else x.upper() for x in list(experiment)])
print(output)
or, simply use swapcase function
experiment = "ChocoLate"
print(experiment.swapcase())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.