Python string.istitle() 函数用法

2023-09-17 22:21:48

istitle() 方法检查每个单词的第一个字符是否为大写,其余字符是否为小写。如果字符串是标题大小写的,则返回 True;否则,它将返回 False。符号和数字将被忽略。

语法:(Syntax:)

str.istitle()

参数:

没有。

返回值:

如果字符串的标题大小写,则返回布尔值 True,否则返回 False。

下面的示例演示 istitle() 方法。

>>> greet='Hello World'
>>> greet.istitle()
True
>>> greet='Hello WORLD'
>>> greet.istitle()
False
>>> greet='hello world'
>>> greet.istitle()
False
>>> greet='HelloWorld'
>>> greet.istitle()
False
>>> s='Python Is A Programming Language'
>>> s.istitle()
True

如果第一个字符是数字或特殊符号,则它将被视为大写字母。

\t
>>> addr='#1 Harbor Side'
>>> addr.istitle()
True
>>> addr='1 Central Park'
>>> addr.istitle()
True

空字符串、数字字符串或仅包含符号的字符串不被视为标题大小写。

\t
>>> empt=''
>>> empt.istitle()
False
>>> numstr='100'
>>> numstr.istitle()
False
>>> usd='$'
>>> usd.istitle()
False

通常,istitle() 方法与 title() 方法一起使用,以便在将字符串转换为标题大小写之前检查字符串,如下所示。

\t
ustr=input()
if not ustr.istitle():
   ustr = ustr.title()
   print('Converted to TitleCase', ustr)
    
print('You entered a TitleCase string')

本文内容总结: