Reputation:
I got the following homework question: Write a program that picks up from the string user for selection. The program prints the string when the letters in the first half of the string are lowercase and the letters in the second half of the string are capital letters. If the length of the string is odd, the first half will be smaller in one half of the second.
additional instructions: Do not use loops or if conditions. Use a slicing action. Assume that the length of the string is greater than 2.
I used up the following code:
#Input of the text
fullClintStr = input("please enter text: ")
#New str of all the current str just in lower case
lowerCaseStr = fullClintStr.lower()
#New str of all the current str just in upper case
upperCaseStr = fullClintStr.upper();
#Slice from the start to the middle (if str length is odd then it will be included in the first half)
lowerCaseStr = lowerCaseStr[0 : (len(fullClintStr) / 2 + len(fullClintStr) % 2)]
#Slice from middle to the end
upperCaseStr = lowerCaseStr[(len(fullClintStr) / 2 - len(fullClintStr) % 2) : len(fullClintStr)]
#Combine both string to new string that itrs firs half is lower case and the #other is upper case
combinedResultStr = lowerCaseStr + "" + uupperCaseStr
#Print he results
print(combinedResultStr)
but faced an error from the type:" slice indices must be integers or None or have an index method"
I would like to know how it can possibly be done. Thank you very much!
Upvotes: 1
Views: 3586
Reputation: 580
This code will work for your needs. Hope it helps:
fullClintStr = input("please enter text: ")
strlen = len(fullClintStr)
lowerCaseStr = fullClintStr.lower()
upperCaseStr = fullClintStr.upper()
cutlen = strlen - (strlen//2)
printStr = lowerCaseStr[:cutlen] + upperCaseStr[cutlen:]
print(printStr)
Upvotes: 1
Reputation: 1834
Your main issue is you are trying to use find the middle point of the list but are not actually getting the length of the string. Consider the script below:
fullClintStr = input("please enter text: ")
list_string = []
for index, element in enumerate(fullClintStr):
if len(fullClintStr) % 2 == 0:
if index < len(fullClintStr)/2:
list_string.append(element.upper())
else:
list_string.append(element.lower())
else:
if index < (len(fullClintStr)/2) - 1:
list_string.append(element.upper())
else:
list_string.append(element.lower())
input_string = ''.join(list_string)
print(input_string)
By wrapping the string using the len command, we can see what the length of the script is. As you said in your problem, you cannot use loops of if statements to solve the problem, but this should give you an idea on how you should approach finding the middle point.
Upvotes: 0
Reputation: 468
fullClintStr
is a string and so if you are trying to access substrings using index numbers what you are looking to do is len(fullClintStr)
instead.
Upvotes: 0