1

我试图通过大写数组中的每个字符来操作一个单词,但是当涉及到一个具有两个相同字符的单词时,它会使它们都大写而不是一个。不是一个只想学习 python 的程序员。预先感谢!

answer = raw_input("What is your word? ")
x = 0
answerWord = ''.join(answer)
while (x < len(answer)):
    if (answerWord[x] != answerWord[x].upper()):
        letter = answerWord.replace(answer[x], answer[x].upper())
    print letter
    x = x + 1

What is your word? boot
Boot
bOOt
bOOt
booT

What is your word? crazy
Crazy
cRazy
crAzy
craZy
crazY
4

3 回答 3

0

answerWord.replace('X', 'Y')将替换字符串中的所有实例。因此,程序的第 6 行采用了整个单词,并将当前正在考虑的字母的所有实例替换为等效的大写字母。XYanswerWord

从您的变量名称看来,您希望变量letter是单个字母,而不是整个单词。也许您的意思是第 6 行的内容如下:

letter = answer[x].upper()

玩得开心!

于 2012-11-15T07:53:39.970 回答
0
for i in range(len(answer)):
    print answer[0:i]+answer[i].upper()+answer[i+1:]
于 2012-11-18T10:12:42.910 回答
0
answer = raw_input("What is your word? ")

for char in range(len(answer)):
    letter = answer[0:char] + answer[char].upper() + answer[char+1:]
    print letter

那应该做的事情,它将每个字母一个一个地更改为大写,然后打印它们。此外,在您的示例中,如果您使用一个已经包含大写字母的单词(例如“Peanuts”),则会引发错误,因为“if”句子不是 True,因此letter是未定义的。

如果您希望大写字母变为小写,而小写字母变为大写等,请使用以下命令:

answer = raw_input("What is your word? ")

for char in range(len(answer)):
    if answer[char] == answer[char].lower():
        letter = answer[0:char] + answer[char].upper() + answer[char+1:]
    else:
        letter = answer[0:char] + answer[char].lower() + answer[char+1:]
    print letter

另请注意,如果您不打算将其letter用于打印以外的任何内容,则只需将两个字母定义都替换为简单的打印,然后将其print letter完全删除。

if answer[char] == answer[char].lower():
    print answer[0:char] + answer[char].upper() + answer[char+1:]
else:
    print answer[0:char] + answer[char].lower() + answer[char+1:]
于 2012-11-18T10:34:27.907 回答