Python字符串title()

时间:2020-02-23 14:43:31  来源:igfitidea点击:

Python字符串title()函数返回字符串的标题大小写版本。
单词的第一个字符用大写字母表示,其余所有字符用小写字母表示。

Python字符串title()

此函数不接受任何参数。
我们来看一些title()函数的示例。

s = 'Python is Good!'
print(s.title())

s = 'PYTHON IS GOOD'
print(s.title())

输出:

Python Is Good!
Python Is Good

此函数将单词的简单语言独立定义作为连续字母的组使用。
因此,撇号(')被视为单词边界。
让我们看看当我们的字符串包含撇号时会发生什么。

s = "Let's go to Party"
print(s.title())

大多数情况下,我们不希望这种情况发生。
我们可以使用正则表达式定义一个将字符串转换为大小写的标题的函数。

import re

def titlecase(s):
  return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
                lambda mo:
                mo.group(0)[0].upper() +
                mo.group(0)[1:].lower(), s)

s = "Let's go to Party"
print(titlecase(s))
print(titlecase('Python is Good!'))
print(titlecase('PYTHON IS GOOD'))

输出:

Let's Go To Party
Python Is Good!
Python Is Good