问题描述
我目前有这个代码
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)
但 .upper 行似乎没有效果,谁能告诉我为什么?
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
推荐答案
.upper()
和 .lower()
函数不会修改原来的 字符串
.根据文档,
The .upper()
and .lower()
functions do not modify the original str
. Per the documentation,
对于.upper()
:
str.upper()
返回字符串的副本,其中所有大小写字符都转换为大写.
Return a copy of the string with all the cased characters converted to uppercase.
对于.lower()
:
str.lower()
返回字符串的副本,其中所有大小写字符都转换为小写.
Return a copy of the string with all the cased characters converted to lowercase.
所以如果你想要分别的大写和小写字符,你需要打印lines[o][p][u].upper()
和lines[o][p][u].lower()
而不是 lines[o][p][u]
.但是,如果我从您的代码示例中正确理解了您的目标,那么您似乎正在尝试从字符串输入中交替使用大写和小写字符.使用列表理解 类似以下内容:
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)
使用以下示例输出:
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']
这篇关于.upper 在 python 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!