我的代码假设将一个字符串带到一个函数,然后将每个字符的大写字母从h切换到H和E到e 但是我的if有点错误 那是为什么?
这是错误消息:
chr = str[i]
TypeError:字符串索引必须是整数,而不是str
我的代码是:
def CapsChanger(str):
i = str[0]
for i in str :
chr = str[i]
if((ord(chr) > 46) and (ord(chr) < 91)):
str[i].upper()
if((ord(chr) > 96) and (ord(chr) < 126)):
str[i].lower()
print str
str = raw_input()
CapsChanger(str)
input()
答案 0 :(得分:3)
执行for i in str
时,每次迭代i
代表实际字符,而不是索引。所以你不需要做chr = str[i]
- i
已经是那个角色了。
答案 1 :(得分:1)
import string
def invertCase(text):
## Creating a list where results will be stored
results = list()
## This will contain the abc in upper and lowercase: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abc = string.lowercase + string.uppercase
## Looping each letter of the received text
for letter in text:
## If the current letter of the loop exists in our abc variable contents, it means it's a letter and not a symbol or space
## So we can apply upper() or lower() to the letter.
if letter in abc:
## If the letter is currently uppercase, then we turn it into lowercase
if letter.isupper():
results.append(letter.lower())
## If the letter is currently lowercase, then we turn it into uppercase
else:
results.append(letter.upper())
## The current letter of the loop is not in our abc variable so it could be anything but a letter
## So we just append it to our results list
else:
results.append(letter)
## Once the loop finishes we just join every item in the list to make the final string and return it
return ''.join(results)
print invertCase('SoMeOnE Is hAvING fUN')
输出:
sOmEoNe iS HaVing Fun
答案 2 :(得分:0)
i
是string
,而不是index
。如果您需要index
使用enumerate
:
for idx, i in str:
print idx, i
ord(chr)
使用代表字母的string
。
如果条件使用Chained Comparisons
,则选择两个。
def CapsChanger(str):
out = []
for idx,chr in enumerate(str):
if 'Z' >= chr >= 'A':
out.append(chr.lower())
elif 'z' >= chr >= 'a':
out.append(chr.upper())
print(''.join(out))
答案 3 :(得分:0)
变量i已经是1个字符的字符串,因为for循环以这种方式处理字符串。此外,当你调用str [i] .upper()时,它需要被分配给某个东西,或者打印出来,否则角色永远不会被实际更改到位。 .lower()和.upper()也有一个已经为你检查范围的行为,并返回相同的字符。例如。如果它已经是大写或数字,则upper()将返回相同的字符。
您的功能可简化如下:
import sys
def CapsChanger(str):
for i in str:
sys.stdout.write (i.lower() if (i.upper() == i) else i.upper())
print
str = raw_input()
CapsChanger(str)
sys.stdout.write
用于避免打印出额外的空格。三元运算符用于一次性切换案例:
<value1> if <condition> else <value2>