2

我是编程新手,我需要一些帮助才能获得免费的在线教程来学习 Python。我正在构建自己的方法来将输入字符串转换为所有小写。我不能使用 string.lower() 方法。在我到目前为止的代码中,我无法弄清楚如何将输入字符串分成可以输入到我的字符转换器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
4

5 回答 5

3

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.

于 2013-08-22T16:48:57.497 回答
1

您只返回第一个字母,您必须return在外部范围内,试试这个,最好使用+=而不是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
于 2013-08-22T16:53:24.420 回答
1

提示:您不需要使用 ord()。Python可以直接做如下对比:

if char >= 'A' and char<='Z':

于 2013-08-22T16:58:26.067 回答
0

我的解决方案:

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))
于 2016-09-24T16:10:12.663 回答
0

尝试这样的事情:

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
于 2018-03-16T19:57:32.840 回答