python确保单词大写

2024-04-25 20:00:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力确保键入的每个单词都像ABC一样大写。我使用的代码是

abbreviate=input("Abbreviation: ")
words=abbreviate[0:6]
numbers = abbreviate[6:8]
if len(abbreviate)==9:
    if words.isalpha: #I think it's also possible to use.if str(words)?
        if words.isupper: #(i did upper first, what is the difference?)
            if int(numbers):
                print("correct")
            else:
                 print("wrong, you need numbers")
        else:
             print("wrong, all words are supposed to be uppercase")
    else:
         print("wrong, it needs to be words(alphabet)") 
else:
     print("wrong, the length needs to be 8")    

QWERTY567应该是正确的。 qwerty567应该不正确。 我该怎么做呢

qwerty333 012345678


Tags: theto键入ifitbe单词else
3条回答

^{}^{}方法。您需要给他们打电话以获得结果:

if words.isalpha():
    if words.isupper():

关于您的评论

I think it's also possible to use if str(words)?

不,str(words)什么也做不了^{}返回一个字符串,因此words已经是一个字符串

I did upper first, what is the difference?

^{}字符串转换为大写,例如'a'.upper() == 'A'


顺便说一下

int()不返回布尔值。最好使用^{}检查numbers是否为数字

使用保护子句比使用嵌套条件更简单:

if len(abbreviate) != 9:
    print("wrong, the length needs to be 9")
elif not words.isalpha():
    print("wrong, the abbreviation must be alphabetic")
...
else:
    print("correct")

IIUC为了验证前5个字符是否为大写字母,后4个字符是否为数字,您可以执行以下操作:

import re

abbreviate=input("Abbreviation: ")

if(re.match(r"^[A-Z]{5}\d{4}", abbreviate)):
    print("correct!")
else:
    print("wrong!")

此外,如果您想确保总共只有9个字符(即输入首先由5个大写字母组成,然后是4个数字),您可以执行以下操作:

import re

abbreviate=input("Abbreviation: ")

if(re.match(r"^[A-Z]{5}\d{4}$", abbreviate)):
    print("correct!")
else:
    print("wrong!")

使用正则表达式:

^[A-Z0-9]+$

a demo on regex101.com

相关问题 更多 >