Reputation: 117
I am new to programming and I need some help for an free online tutorial to learn Python. I am building my own method to convert a an input string to all lower cases. I cannot use the string.lower() method. In the code I have so far I cannot figure out how to separate the input string into characters that can be inputed into my character converter lowerChar(char).
string=input #input string
def lowerChar(char): #function for converting characters into lowercase
if ord(char) >= ord('A') and ord(char)<=ord('Z'):
return chr(ord(char) + 32)
else:
return char
def lowerString(string): #function for feeding characters of string into lowerChar
result = ""
for i in string:
result = result + lowerChar(string[i])
return result
Upvotes: 2
Views: 4218
Reputation: 1
Try something like this:
def lowerChar(c):
if 'A' <= c <= 'Z':
return chr(ord(c) - ord('A') + ord('a'))
else:
return c
def lowerString(string):
result = ""
x=0
for i in string:
while x < len(string):
result = result + lowerChar(string[x])
x+=1
return result
Upvotes: 0
Reputation: 17
My solution:
string = input("Input one liner: ")
def lowerChar(char):
if char >= 65 and char <= 90:
char = chr(char + 32)
return char
else:
char = chr(char)
return char
def lowerString(string):
result = ""
for i in range(0, len(string)):
result = result + lowerChar(ord(string[i]))
return result
print(lowerString(string))
Upvotes: 0
Reputation: 41
A tip: You don't need to use ord(). Python can directly do the following comparision:
if char >= 'A' and char<='Z':
Upvotes: 1
Reputation: 5186
You are really close:
def lowerString(string):
result = ""
for i in string:
# i is a character in the string
result = result + lowerChar(i)
# This shouldn't be under the for loop
return result
Strings are iterable just like lists!
Also, make sure to be careful about your indentation levels, and the number of spaces you use should be consistent.
Upvotes: 3
Reputation:
You are returning only the first letter, you have to return
in a outer scope, try this, also it is better to use +=
instead of result = result + lowerChar(i)
def lowerString(string): #function for feeding characters of string into lowerChar
result = ""
for i in string:
result += lowerChar(i)
return result
print lowerString("HELLO") #hello
Upvotes: 1