.upper not working in python

孤街浪徒 提交于 2019-12-13 11:21:23

问题


I currently have this code

num_lines = int(input())
lines = []
tempy = ''
ctr = 1
abc = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
}
for i in range(0, num_lines):
  tempy = input()
  lines.append([])
  lines[i].append(tempy)


for o in range(0, num_lines):
  for p  in range(0, len(lines[o])):
    for u in range(0, len(lines[o][p])):
      if lines[o][p][u] in abc:
        lines = str(lines)
        if ctr % 2 == 0:
          print(lines[o][p][u])
          lines[o][p][u].upper()
        else:
          print(lines[o][p][u])
          lines[o][p][u].lower()
        ctr += 1

print(lines)

but the .upper line does not seem to have effect, can anyone please tell me why?

Thank you in advance, and if there is an answer already please kindly tell me that instead of marking as a duplicate cause I did search for a good hour


回答1:


The .upper() and .lower() functions do not modify the original str. Per the documentation,

For .upper():

str.upper()

Return a copy of the string with all the cased characters converted to uppercase.

For .lower():

str.lower()

Return a copy of the string with all the cased characters converted to lowercase.

So if you want the uppercase and lowercase characters respectively, you need to print lines[o][p][u].upper() and lines[o][p][u].lower() as opposed to lines[o][p][u]. However, if I correctly understand your objective, from your code sample, it looks as though you're trying to alternate uppercase and lowercase characters from string inputs. You can do this much more easily using list comprehension with something like the following:

num_lines   = int(input("How many words do you want to enter?: "))
originals   = []
alternating = []

for i in range(num_lines):

    line = input("{}. Enter a word: ".format(i + 1))
    originals.append(line)
    alternating.append("".join([x.lower() if j % 2 == 0 else x.upper() for j, x in enumerate(line)]))

print("Originals:\t",   originals)
print("Alternating:\t", alternating)

With the following sample output:

How many words do you want to enter?: 3
1. Enter a word: Spam
2. Enter a word: ham
3. Enter a word: EGGS
Originals:       ['Spam', 'ham', 'EGGS']
Alternating:     ['sPaM', 'hAm', 'eGgS']


来源:https://stackoverflow.com/questions/47026581/upper-not-working-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!