在没有内置函数的情况下将字符串转换为所有小写

时间:2018-11-10 03:36:09

标签: python string

#variable defination#
lower="abcdefghijklmnopqrstuvwxyz"
upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
valid=True
x=0
g=0


string=input("enter a string:")

#data validation#
for char in string:
  if char in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ":
     valid=True
  else:
     valid=False

#finding the character#
if valid:
  for char in string:
    g+=1
    for ele in upper:
      if char!=ele:
       x+=1


print(lower[x]+string[g::])

**我无法使用它,它会不断迭代整个字符串,而不会满足任何条件。 **

4 个答案:

答案 0 :(得分:1)

我试图最小化对原始代码的更改(但是请记住,其他解决方案显然要好得多。)

#variable defination#
lower="abcdefghijklmnopqrstuvwxyz"
upper="ABCDEFGHIJKLMNOPQRSTUVWXYZ"

string=input("enter a string:")

#data validation#
valid = True
for char in string:
  if char not in lower + upper:
     valid=False

#finding the character#
if valid:
  result = ""
  for char in string:
    if char in lower:
      result += char
    else:
      # uppercase character
      for i in range(len(upper)):
        if char == upper[i]:
          result += lower[i]
          break

  print(result)

答案 1 :(得分:0)

由于允许使用小写和大写字符输入,因此可以在它们之间创建字典映射,并结合列表理解使用f = lambda x: 0 if x>100 else 1 df['my_column'] = df['my_column'].map(f)

str.join

尚不清楚这是否满足您的“无内置功能”要求。

答案 2 :(得分:0)

您可以在uppercaselowercase字母之间创建映射(字典),以便upper_to_lower[uppercase]应该给您lowercase。不过,您可以参考以下实现。

import string

def to_lower_case(word):
    # construct auxilliary dictionary to avoid ord and chr built-in methods
    upper_to_lower = {}
    for index in range(len(string.ascii_uppercase)): # this is 26 we can use it as constant though
        upper_to_lower[string.ascii_uppercase[index]] = string.ascii_lowercase[index]

    result = ''
    for alphabet in word:
        if alphabet in string.ascii_uppercase:
            result += upper_to_lower[alphabet]
        else:
            result += alphabet

    return result

# sample input
In [5]: to_lower_case('ANJSNJN48982984aadkaka')                                
Out[5]: 'anjsnjn48982984aadkaka'

答案 3 :(得分:0)

您还可以编写index方法来获取upper字符串中大写字符的索引:

lower = "abcdefghijklmnopqrstuvwxyz"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def index(char):
    i = 0
    for c in upper:
        if char == c: return i
        i += 1

然后您可以将字符串转换为小写:

#data validation#
# ...

#finding the character#
s = ''
if valid:
    for char in string:
        if char in lower: s += char
        else: s += lower[index(char)]

print(s)