首页 › Python 实例 › 大小写转换与判断

Python 大小写转换与判断

字符串实例 021

题目

演示字符串常用的大小写转换方法和内容判断方法。

参考代码

s = "hello Python world"
print(s.upper())
print(s.lower())
print(s.title())
print(s.capitalize())
print("Hello".swapcase())

for t in ["Python3", "12345", "hello", "HELLO", "  "]:
    print(f"{t!r:10} isalnum={t.isalnum()} isdigit={t.isdigit()} "
          f"islower={t.islower()} isupper={t.isupper()} isspace={t.isspace()}")
执行以上代码输出结果为:
HELLO PYTHON WORLD
hello python world
Hello Python World
Hello python world
hELLO
'Python3'  isalnum=True isdigit=False islower=False isupper=False isspace=False
'12345'    isalnum=True isdigit=True islower=False isupper=False isspace=False
'hello'    isalnum=True isdigit=False islower=True isupper=False isspace=False
'HELLO'    isalnum=True isdigit=False islower=False isupper=True isspace=False
'  '       isalnum=False isdigit=False islower=False isupper=False isspace=True

代码解析

这些方法都返回新字符串,原字符串不会改变。isxxx() 系列方法在字符串为空时都返回 False。