Python字符串title()

Python String title()

Python String title()

Python字符串title()

Python String title() function returns a title cased version of the string. The first character of the words are in Uppercase and all the remaining characters are in Lowercase.

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

Python字符串title() (Python String title())

This function doesn’t accept any argument. Let’s look at some examples of title() function.

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

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

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

Output:

输出:

Python Is Good!
Python Is Good

This function uses a simple language-independent definition of a word as groups of consecutive letters. So apostrophes (‘) is treated as a word boundary. Let’s see what happens when our string contains an apostrophe.

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

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

Output: Let'S Go To Party

输出: Let'S Go To Party

Most of the times we don’t want this to happen. We can use a regular expression to define a function to convert a string into title cased.

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

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'))

Output:

输出:

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

If you are not familiar with lambda expressions, please read lambda in Python.

如果您不熟悉lambda表达式,请阅读Python中的lambda

GitHub Repository. GitHub存储库中签出更多Python示例。

Official Documentation: title()

官方文件: title()

翻译自: https://www.journaldev.com/24537/python-string-title

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值