英文:
How do I alternate the cases of letters/words in a list?
问题
我需要将 "letter_guessed" 输入转换为小写,如果它是大写的,并且已经存在一个大写字母作为小写字母存在于列表中,那么它将返回 false,但我无法让它正常工作。
我尝试过使用 isupper()
、upper
、islower()
、lower()
以多种方式。我相当确定我在 "if" 方面做错了些什么,但无法弄清楚正确的方式。
def check_valid_input(letter_guessed, old_letters_guessed):
while True:
"""只有当输入一个字母且不包含除了字母 'abc' 之外的特殊字符,且未被输入过时,才会起作用"""
if len(letter_guessed) == 1 and letter_guessed not in old_letters_guessed:
"""如果输入的是一个字母且尚未在 old_letter_guessed 中,则继续"""
old_letters_guessed.append(letter_guessed)
print("True")
letter_guessed = input(" : ")
else:
"""如果输入错误,将打印 False 并提示重新尝试,如果输入正确,则返回到上面的 'if'"""
print(False, '请重试')
old_letters_guessed.sort()
print('->'.join(old_letters_guessed))
letter_guessed = input(" : ")
new = input()
old = []
check_valid_input(new, old)
希望这可以帮助你解决问题。
英文:
I need to convert the "letter_guessed" input to lower case, if it's uppercase and if an uppercase letter already exists inside the list as a lower case it will return false but I can't get it to work.
I have tried using isupper()
, upper
,islower()
, lower()
in many ways. I am pretty sure that I am doing something wrong with "if" but can't get it right.
def check_valid_input(letter_guessed, old_letters_guessed):
while True:
""" will work only if you enter one letter and do not contain special letters other then the abc
and if its all ready been entered it will show false """
if len(letter_guessed) == 1 and letter_guessed not in old_letters_guessed :
"""if the letter is one letter and not already inside old_letter_guessed only then continue """
old_letters_guessed.append(letter_guessed)
print("True")
letter_guessed = input(" : ")
else:
""" if its wrong input will print False Try again and if the input is correct it will go back to " if " """
#old_letters_guessed.append(letter_guessed)
print(False, 'Try again')
old_letters_guessed.sort()
print('->'.join(old_letters_guessed))
letter_guessed = input(" : ")
#if letter_guessed is letter_guessed.isupper()
new = input()
old = []
check_valid_input(new,old)
答案1
得分: 1
"swapcase" 是一个用于在大写和小写之间切换的方法。所以:
"TEST".swapcase()
会变成
"test"
我建议使用这个方法,而不是你的 if 语句。
英文:
Everything sting has a method called swapcase which swaps between upper and lower case. So:
"TEST".swapcase()
Would become
"test"
I'd suggest using that instead of your if statements.
答案2
得分: 0
使用for循环迭代列表中的所有元素,并使用.swapcase()
函数,该函数适用于所有字符串。
list = ['some', 'words', 'in a list']
for word in list:
print(word.swapcase())
英文:
use a for loop to iterate over all elements in the list with the .swapcase()
function common to all strings
list = ['some', 'words', 'in a list']
for word in list:
print(word.swapcase())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论