str类提供了许多有用的方法,用于处理和组合字符串。这些操作包括查找、清理、拆分、转换、翻译,以及许多其他技巧。
字符串是Unicode 码点的序列:单个“字符”或码点(长度为 1 的字符串)可以用从左数起的0-based index编号引用,也可以用从右数起的-1-based index编号引用。字符串实现了所有通用序列操作。
可以使用for item in <str>或for index, item in enumerate(<str>)语法遍历字符串,也可以用<str> + <other str>或<str>.join(<iterable>)进行拼接。
字符串是_不可变的_,也就是说,内存中str对象的值无法改变。作用于str的函数或方法(比如我们这里正在学习的这些)不会修改原来的str,而是返回该str对象的一个新instance。
下面是一小部分 Python 字符串方法。完整列表请参见 Python 文档中的str 类。
<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>.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>.strip(<chars>)返回str的一个副本,并移除开头和结尾的<chars>。
<chars>中指定的码点并不是前缀或后缀,这些码点的所有组合都会从字符串的两端被移除。
如果没有为<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'
在这个练习中,你要帮妹妹修改她的学校论文。老师希望标点正确、语法无误,用词也要出色。
你有四个任务,需要整理和修改字符串。
一篇好论文需要一个格式规范的标题。
实现函数capitalize_title(<title>),它接受一个标题str作为形参,并把每个单词的首字母大写。
这个函数应返回一个采用标题式大写格式的str。
>>> capitalize_title("my hobbies")
"My Hobbies"
你想确保论文里的标点完全正确。
实现函数check_sentence_ending(),它接受sentence作为形参。这个函数应返回一个bool。
>>> check_sentence_ending("I like to hike, bake, and read.")
True
为了让论文看起来更专业,需要去掉多余的空格。
实现函数clean_up_spacing(),它接受sentence作为形参。
这个函数应去掉句子开头和结尾的多余空白,并返回更新后的新句子str。
>>> clean_up_spacing(" I like to go on hikes with my dog. ")
"I like to go on hikes with my dog."
为了让论文_更出色_,你可以把一些形容词换成它们的同义词。
编写函数replace_word_choice(),它接受sentence、old_word和new_word作为形参。
这个函数应把所有出现的old_word替换为new_word,并返回一个包含更新后句子的新str。
>>> replace_word_choice("I bake good cakes.", "good", "amazing")
"I bake amazing cakes."