字符

字符串方法 属于 Python

60 个练习

关于 字符串方法

str 是由 Unicode 码点 组成的不可变序列。其中可以包括字母、变音符号、定位字符、数字、货币符号、emoji、标点、空格和换行符等等。

字符串实现了所有通用序列操作,并且可以用 for item in <str> 或 for index, item in enumerate(<str>) 语法进行迭代。单个码点(长度为 1 的字符串)可以用从左数起的 0-based index 编号引用,也可以用从右数起的 -1-based index 编号引用。

字符串可以用 <str> + <other str> 或 <str>.join(<iterable>) 拼接,也可以用 <str>.split(<separator>) 拆分。它们还提供了许多其他的格式化和组装选项。

为了进一步处理字符串,Python 提供了一套丰富的字符串方法,用于搜索、清理、转换、翻译以及许多其他操作。

一些比较常用的 str 方法包括:

  • 用 <str>.startswith(<substr>) 和 <str>.endswith(<substr>) 检查前缀或后缀
  • 用 <str>.title()、<str>.upper()/<str>.lower() 和 <str>.swapcase() 等方法改变字符串的大小写
  • 用 <str>.strip(<chars>)、<str>.lstrip(<chars>) 或 <str>.rstrip(<chars>) 删除字符串开头或结尾的字符
  • 用 <str>.replace(<old>, <new>) 方法替换子字符串

由于字符串是_不可变_的,str 对象在内存中的值无法改变;那些看起来会修改字符串的方法,返回的是该 str 对象的一个新副本或新实例。

<str>.endswith(<suffix>) 在字符串以 <suffix> 结尾时返回 True,否则返回 False。

>>> 'My heart breaks. 💔'.endswith('💔')
True

>>> 'cheerfulness'.endswith('ness')
True

# Punctuation is part of the string, so needs to be included in any endswith match.
>>> 'Do you want to 💃?'.endswith('💃')
False

>>> 'The quick brown fox jumped over the lazy dog.'.endswith('dog')
False

<str>.title() 会解析字符串,并把找到的每个“单词”的第一个“字符”大写。 在 Python 中,这很大程度上取决于所使用的语言编解码器,以及具体语言如何表示单词和字符。 某种语言或字符集可能还有区域设置规则。

>>> man_in_hat_th = 'ผู้ชายใส่หมวก'
>>> man_in_hat_ru = 'мужчина в шляпе'
>>> man_in_hat_ko = '모자를 쓴 남자'
>>> man_in_hat_en = 'the man in the hat.'

>>> man_in_hat_th.title()
'ผู้ชายใส่หมวก'

>>> man_in_hat_ru.title()
'Мужчина В Шляпе'

>>> man_in_hat_ko.title()
'모자를 쓴 남자'

>> man_in_hat_en.title()
'The Man In The Hat.'

<str>.strip(<chars>) 返回 str 的一个副本,并删除开头和结尾的 <chars>。 <chars> 中指定的码点并不是前缀或后缀,从字符串的两端开始,这些码点的所有组合都会被删除。 如果没有为 <chars> 指定任何内容,则会删除空白码点的所有组合。 如果只想删除左侧或右侧,可以使用 <str>.lstrip(<chars>) 和 <str>.rstrip(<chars>)。

# This will remove "https://", because it can be formed from "/stph:". 
>>> 'https://unicode.org/emoji/'.strip('/stph:')
'unicode.org/emoji'

# Removal of all whitespace from both ends of the str.
>>> '   🐪🐪🐪🌟🐪🐪🐪   '.strip()
'🐪🐪🐪🌟🐪🐪🐪'

>>> justification = 'оправдание'
>>> justification.strip('еина')
'оправд'

# Prefix and suffix in one step.
>>> 'unaddressed'.strip('dnue')
'address'

>>> '  unaddressed  '.strip('dnue ')
'address'

<str>.replace(<substring>, <replacement substring>) 返回字符串的一个副本,其中所有出现的 <substring> 都被替换为 <replacement substring>。

下面引用的诗句出自 Lewis Carroll 的 The Hunting of the Snark

# The Hunting of the Snark, by Lewis Carroll
>>> quote = '''
"Just the place for a Snark!" the Bellman cried,
   As he landed his crew with care;
Supporting each man on the top of the tide
   By a finger entwined in his hair.

"Just the place for a Snark! I have said it twice:
   That alone should encourage the crew.
Just the place for a Snark! I have said it thrice:
   What I tell you three times is true."
'''

>>> quote.replace('Snark', '🐲')
...
'\n"Just the place for a 🐲!" the Bellman cried,\n   As he landed his crew with care;\nSupporting each man on the top of the tide\n   By a finger entwined in his hair.\n\n"Just the place for a 🐲! I have said it twice:\n   That alone should encourage the crew.\nJust the place for a 🐲! I have said it thrice:\n   What I tell you three times is true."\n'

>>> 'bookkeeper'.replace('kk', 'k k')
'book keeper'

🌟Python 3.9 新增内容

Python 3.9 引入了两个新的字符串方法,让删除前缀和后缀变得容易得多。

<str>.removeprefix(<substring>) 返回去掉前缀后的字符串(string[len(<substring>):])。如果 <substring> 不存在,则返回原字符串的副本。

# removing a prefix
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'bookkeeper'.removeprefix('book')
'keeper'

<str>.removesuffix(<substring>) 返回去掉后缀后的字符串(string[:-len(substring)])。如果 <substring> 不存在,则返回原字符串的副本。

# removing a suffix
>>> 'TestHook'.removesuffix('Hook')
'Test'
>>> 'bookkeeper'.removesuffix('keeper')
'book'

如果想看更多示例和方法,非正式教程 是个不错的起点。 Python 文档中的 How to Unicode 详细介绍了 Unicode、编码、字节以及其他在 Python 中处理字符串的技术要点。

Python 还通过 re 模块支持正则表达式,我们会在以后的概念中介绍。

通过 GitHub 编辑 该链接会在新窗口或标签页中打开

学习 字符串方法

练习已锁定

再解锁 3 个练习即可练习 字符串方法