3小时入门Python——第二十八课字符串的基本操作
如您所知,字符串是 Python 中最重要的数据类型之一。为了使使用字符串更容易,Python 有许多特殊的内置字符串方法。我们将学习其中的一些。
但是要记住的重要一点是,字符串是不可变的数据类型!这意味着您不能只就地更改字符串,因此大多数字符串方法都返回字符串的副本(有几个例外)。要保存对字符串所做的更改以供以后使用,您需要为创建的副本创建一个新变量,或为该副本分配相同的名称。因此,如何使用方法的输出取决于您是要使用原始字符串还是稍后使用其副本。
“更改”字符串
第一组字符串方法由以特定方式“更改”字符串的方法组成,也就是说,它们返回进行了某些更改的副本。
调用方法的语法如下:首先给出一个字符串(或一个包含字符串的变量的名称),然后是一个句点,其后是方法名称和括号,其中列出了参数。
这是这种常见的字符串方法的列表:
- **
str.replace(old, new[, count])
**用一个替换所有出现的old
字符串new
。该count
参数是可选的,如果指定,count
则在给定的字符串中仅替换第一次出现的参数。 str.upper()
将字符串的所有字符转换为大写。str.lower()
将字符串的所有字符转换为小写。str.title()
将每个单词的第一个字符转换为大写。str.swapcase()
将大写转换为小写,反之亦然。str.capitalize()
将字符串的第一个字符更改为标题大小写,其余更改为小写。
这是如何使用这些方法的示例(请注意,我们不会保存每个方法的结果):
message = "bonjour and welcome to Paris!"
print(message.upper()) # BONJOUR AND WELCOME TO PARIS!
# `message` is not changed
print(message) # bonjour and welcome to Paris!
title_message = message.title()
# `title_message` contains a new string with all words capitalized
print(title_message) # Bonjour And Welcome To Paris!
print(message.replace("Paris", "Lyon")) # bonjour and welcome to Lyon!
replaced_message = message.replace("o", "!", 2)
print(replaced_message) # b!nj!ur and welcome to Paris!
# again, the source string is unchanged, only its copy is modified
print(message) # bonjour and welcome to Paris!
“编辑”字符串
通常,当您从某处(文件或输入)读取字符串时,需要对其进行编辑,以使其仅包含所需的信息。例如,输入字符串可能有很多不必要的空格或字符的某些尾随组合。在“编辑”的方法,可以提供帮助的是**strip()
,rstrip()
和 lstrip()
**。
- **
str.lstrip([chars])
**删除前导字符(即左侧的字符)。如果chars
未指定参数,则将删除前导空格。 - **
str.rstrip([chars])
**删除尾随字符(即右侧的字符)。参数的默认值chars
也是空白。 - **
str.strip([chars])
**删除开头和结尾字符。默认为空格。
该 chars
参数,指定时,是意在从最末端删除或字(取决于你使用的方法)的开始字符的字符串。看看它怎么运作:
whitespace_string = " hey "
normal_string = "incomprehensibilities"
# delete spaces from the left side
whitespace_string.lstrip() # "hey "
# delete all "i" and "s" from the left side
normal_string.lstrip("is") # "ncomprehensibilities"
# delete spaces from the right side
whitespace_string.rstrip() # " hey"
# delete all "i" and "s" from the right side
normal_string.rstrip("is") # "incomprehensibilitie"
# no spaces from both sides
whitespace_string.strip() # "hey"
# delete all trailing "i" and "s" from both sides
normal_string.strip("is") # "ncomprehensibilitie"
请记住,方法 strip()
,lstrip()
并 rstrip()
摆脱所有可能的指定字符组合:
word = "Mississippi"
# starting from the right side, all "i", "p", and "s" are removed:
print(word.rstrip("ips")) # "M"
# the word starts with "M" rather than "i", "p", or "s", so no chars are removed from the left side:
print(word.lstrip("ips")) # "Mississippi"
# "M", "i", "p", and "s" are removed from both sides, so nothing is left:
print(word.strip("Mips")) # ""
小心使用它们,否则您可能会得到一个空字符串。
结论
因此,我们考虑了字符串的主要方法。这是一个简短的回顾:
- 在使用字符串时,必须记住字符串是不可变的,因此所有“更改”它们的方法仅返回具有必要更改的字符串副本。
- 如果要保存方法调用的结果以供以后使用,则需要将此结果分配给变量(相同或不同名称的变量)。
- 如果您只想使用一次此结果(例如,在比较中或仅打印格式化的字符串),则可以自由使用该结果,就像我们在中所做的那样
print()
。