个性化阅读
专注于IT技术分析

Python字符串用法教程

点击下载

本文概述

字符串是字母, 单词或其他字符的集合。它是原始数据结构之一, 是进行数据操作的基础。 Python具有一个名为str的内置字符串类。 Python字符串是”不可变的”, 这意味着它们在创建后就无法更改。对于字符串操作, 由于它们的不可变属性, 我们将在创建新字符串时代表计算值。

在本教程中, 你将深入了解字符串, 并将涵盖以下主题:

  • 首先, 你将了解什么是Python字符串以及如何表示它们。
  • 接下来, 你将深入研究String Slicing, 在其中将向你介绍Python中切片和跨步的重要概念。
  • 你还将看到一些常用的字符串操作。
  • 最后, 你将看到各种格式化字符串的方法。你会看见:
    • %格式化
    • 格式化程序类
    • 范本
    • F-string, 这是从Python版本3.6开始的字符串格式家族的最新成员
字符串python教程

如果你想了解有关Python中数据结构的更多信息, 请务必查看srcmini的两部分Python Data Science Toolbox。本课程将更深入地研究函数, 迭代器, 列表等。

字符串

你可以使用str对象在Python中处理文本数据。字符串是unicode的不可变序列。 Unicode是一个旨在表示语言中所有字符的系统。在unicode中, 每个字母, 字符都表示为一个4字节的数字。每个数字代表一个唯一的字符。

为了表示一个字符串, 可以将其用引号引起来。可以有多种方式执行此操作:

  • 单引号, 如本例所示:”单引号允许你在字符串中嵌入”双引号”。
  • 双引号。例如:”双引号允许你在字符串中嵌入”单”引号。”
  • 三重引号, 例如本例:”””使用双引号的三引号”””, ”'”使用单引号的三引号。”

三引号引起来的字符串使你可以使用多个行字符串, 并且所有关联的空格都将包含在字符串中。

single_quote = 'Single quote allow you to embed "double" quotes in your string.'
double_quote = "Double quote allow you to embed 'single' quotes in your string."
triple_quote = """Triple quotes allows to embed "double quotes" as well as 'single quotes' in your string. 
And can also span across multiple lines."""

字符串是不可变的, 这意味着如果你尝试更改字符串中的任何值, 将抛出错误。你必须创建一个新字符串才能合并更改。

triple_quote = '''This is triple quoted string using "single" quotes.'''
triple_quote[35] = "'"
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-207-62d335428dcf> in <module>()
      1 triple_quote = '''This is triple quoted string using "single" quotes.'''
----> 2 triple_quote[35] = "'"


TypeError: 'str' object does not support item assignment
triple_quote_new = triple_quote[0:35] + "'single'" + triple_quote[43:]
print(triple_quote_new)
This is triple quoted string using 'single' quotes.

你可以使用内置的len()函数找到字符串的长度:

len(triple_quote_new)
51

Python中的字符串切片

由于字符串是字符序列, 因此你可以像使用Python列表或元组一样通过切片和索引访问它。相对于字符串中的每个字符对字符串进行索引, 并且索引从0开始:

python字符串教程

在上面的字符串中, 第一个索引为C, 索引为0。最后一个字符为句号。这是字符串中的第16个字符。你还可以从-1开始以相反的方向访问字符, 这意味着你也可以使用-1作为access的索引值。在字符串中。 Chocolate和cookie之间也有一个空格, 它也是字符串的一部分, 并有自己的索引, 在这种情况下为9。你可以使用切片检查。

由于Python字符串中的每个字符都有对应的索引号, 因此你可以按照与其他顺序数据类型相同的方式访问和操作字符串。切片是Python中的一项技术, 可让你使用容器对象的索引值来指定特定元素或元素子集。切片使你不必编写循环语句来遍历字符串的索引来查找或访问某些子字符串。

snack = "Chocolate cookie."
print(snack[0])
print(snack[9])
print(snack[-1])
C

.

假设你想从下面的字符串中提取子字符串” cookie”。你会怎么做?

在这种情况下, 你将使用范围切片。

范围切片的语法如下:[开始索引(包括):停止索引(排除)]

snack = "Chocolate cookie."
print(snack[10:16])
cookie

你也可以对停止索引使用负值来执行此操作:

print(snack[10:-1]) # -1: since the stop index is excluded in slicing.
cookie

在不指定终止索引的情况下进行切片意味着你捕获了从起始索引到句子中最后一个索引的字符。同样, 缺少起始索引的切片意味着你从字符串中的第一个索引开始到终止索引:

# Stop value not provided
print(snack[0:]) 

# Start value not provided (Stop value excluded according to syntax)
print(snack[:-1])

# This is also allowed
print(snack[:])
Chocolate cookie.
Chocolate cookie
Chocolate cookie.

字符串切片也可以接受第三个参数, 即跨度(stride), 它是指从字符串中检索第一个字符后要向前移动多少个字符。步幅的值默认设置为1。

让我们看一下实际行动以更好地理解它:

number_string = "1020304050"
print(number_string[0:-1:2])
12345

提示:跨步可以做的很酷的事情是反向字符串:

print(number_string[::-1]) #
0504030201

跨步的值-1允许你从结束字符开始, 然后一次移动一个字符。

或者, 如果你提供-2作为值, 则从结束字符开始, 并一次移动两个字符:

print(number_string[::-2]) #
00000

常见的字符串操作

切片, 范围切片是你需要对字符串执行的常见操作。还有字符串连接, 就像加法一样简单:

string1 = 'Chocolate'
string2 = 'cookie'

snack = string1 + " " + string2
print(snack)
Chocolate cookie

但是, 如果你尝试将字符串与其他数据类型连接起来, 则此方法将无效。

cost = 15
string1 = "The total in Euro is: "

bill = string1 + cost
print(bill)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-218-7d5c5248b927> in <module>()
      2 string1 = "The total in Euro is: "
      3 
----> 4 bill = string1 + cost
      5 print(bill)


TypeError: Can't convert 'int' object to str implicitly

在这里, 你尝试将字符串与不允许的整数值连接。解释器无法隐式理解你是否要执行简单的整数加法或字符串连接。但是, 请立即尝试以下操作:

bill = string1 + str(cost)
print(bill)
The total in Euro is: 15

这是因为你将整数显式转换为字符串值, 然后应用了串联。要了解有关数据类型转换的更多信息, 请查看本教程。

要重复一个字符串, 请使用*操作。

single_word = 'hip '
line1 = single_word * 2 + 'hurray! '
print(line1 * 3)
hip hip hurray! hip hip hurray! hip hip hurray! 

你还可以使用in和not in在字符串中检查成员资格属性:

sub_string1 = 'ice'
sub_string2 = 'glue'
string1 = 'ice cream'
if sub_string in string1:
    print("There is " + sub_string + " in " + string1)
if sub_string2 not in string1:
    print("Phew! No " + sub_string2 + " in " + string1)
There is ice in ice cream
Phew! No glue in ice cream

Python提供了许多内置方法或辅助函数来操纵字符串。使用这些内置方法可以执行一些操作, 其中包括替换子字符串, 将段落中的某些单词大写, 在另一个字符串中查找字符串的位置。

详细了解其中一些:

  • str.capitalize():返回字符串的副本, 其首字符大写。
str.capitalize('cookie')
'Cookie'
  • str.islower():如果字符串中的所有字符均为小写, 则返回true, 否则返回false。
snack = 'cookie'
snack.islower()
True
  • str.find(substring):返回找到子字符串的字符串中的最低索引。你还可以在想要搜索子字符串的字符串中指定开始和结束索引。如果未找到子字符串, 则返回-1。
str1 = 'I got you a cookie'
str2 = 'cook'
str1.find(str2)
12
  • str.count(substring):计算子字符串在字符串中出现的次数。你还可以指定字符串的开始和结束索引。
str1 = 'I got you a cookie, do you like cookies?'
str2 = 'cookie'
str1.count(str2)
2
  • str.isspace():如果字符串中仅包含空格字符, 则返回True, 否则返回false。空格字符是空格, 制表符, 下一行等字符。

当使用现实数据集时, 这可能很有用, 在从一种格式转换为另一种格式期间, 这些数据集可能并不总是编码正确的间距。

str_space = '   '
str_space.isspace()
True
str_tab = '\t'
str_tab.isspace()
True
str_nextline = '''\n'''
str_nextline.isspace()
True

注意:你是否注意到上面的\ t, \ n?这些称为转义字符。它们以\(反斜杠)开头。在内部, 它们不解释为普通字符串, 而是解释为代表其他内容的特殊字符。例如-\ t代表制表符。还有更多的转义字符, 你可以在这里阅读更多有关它们的信息。

  • str.lstrip():删除字符串中所有前导空格。当你使用真实数据集时, 这是另一个可以方便使用的功能。
str1 = " I can't hear you. Are you alright? "
str2 = " Yes, all is good."
str3 = str1.lstrip() + str2.lstrip()
print(str3)
I can't hear you. Are you alright? Yes, all is good.
  • str.isdigit():如果字符串仅包含数字, 则返回True, 否则返回False。
number_string = "1020304050"
number_string.isdigit()
True
  • str.replace(substring, new):用new替换出现在字符串中的所有子字符串。你还可以定义第三个参数max, 该参数最多替换字符串中子字符串的最大出现次数。请记住, 这不是就地替换, 这意味着不可变属性仍然有效, 并且实际上形成了新字符串。
string1 = 'hip hip hurray! hip hip hurray! hip hip hurray!'
string2 = string1.replace('hip', 'Hip')
print(string1)
print(string2)
hip hip hurray! hip hip hurray! hip hip hurray!
Hip Hip hurray! Hip Hip hurray! Hip Hip hurray!
string1.replace('hip', 'Hip', 2)
'Hip Hip hurray! hip hip hurray! hip hip hurray!'
  • str.split(delimiter =””):根据定界符分割字符串(如果未提供, 则空格)并返回子字符串列表。
dessert = 'Cake, Cookie, Icecream'
list_dessert = string1.split(', ')

你可以在这里找到Python中字符串方法的详尽列表。

字符串格式

Python支持多种格式化字符串的方法。在本节中, 你将了解有关此格式字符串的更多信息!

%格式化

模%是Python中的内置操作。它被称为插值运算符。你将需要提供%, 后跟需要格式化或转换的数据类型。然后, %操作用零个或多个指定数据类型的元素替换’%datatype’短语:

print("I bought %d Euro worth of %s!" %(200, 'cookies'))
I bought 200 Euro worth of cookies!

你已经看到%d用于整数, %s用于字符串。其他可用的转换类型包括:o代表八进制值, x代表十六进制, f代表浮点十进制格式, c代表单个字符(接受整数或单个字符串)。

格式化程序类

格式化程序类是内置字符串类之一。它提供了使用format()方法进行复杂的变量替换和值格式化的功能。它允许你通过重写其中包含的公共方法来创建和自定义自己的字符串格式设置行为:format(), vformat()。它具有一些打算用子类替换的方法:parse(), get_field(), get_value(), check_unused_args(), format_field()和convert_field()。但是, 为简单起见, 你将仅查看操作中最常用的format()函数。

print("I bought {0} Euro worth of {1}!".format(200, 'cookies')) #Accessing values by position
I bought 200 Euro worth of cookies!
print("I bought {total} Euro worth of {item}!".format(total = 200, item = 'cookies')) #Accessing values by name
I bought 200 Euro worth of cookies!
'{:#<10}'.format('Cake') #Left aligment for word 'Cake' according to right alignment, gaps filled with '#'
'Cake######'
'{:#^10}'.format('Cake') #Centre aligment for word 'Cake' according to right alignment, gaps filled with '#'
'###Cake###'
'{:#>10}'.format('Cake') #Right aligment for word 'Cake' according to right alignment, gaps filled with '#'
'######Cake'
for num in range(1, 10): 
        print('{0:{width}}'.format(num, width=5), end=' ')
    1     2     3     4     5     6     7     8     9 

模板字符串

模板支持基于$的替换, 而不是基于普通%的替换。在Python 2.4版中引入模板的基本原理是, 即使%字符串格式化功能强大且丰富, 但它们易于出错, 并且在遵循’%’的格式方面也相当严格, 使其复杂。 %格式化的一个常见错误是忘记了尾随的格式字符, 例如:%(variabl)e中的e。

模板中定义了一些方法:replace()和safe_substitute()。你可以通过以下方式使用它们:

from string import Template #First you will need to import 'Tempalte' class

money = dict(who = 'You', to_whom = 'baker')
Template('$who owe the $to_whom a total of $$100').substitute(money)
'You owe the baker a total of $100'

注意上面示例中的$$吗?

这是因为使用模板$$是转义字符, 将其替换为单个$。这是模板的规则之一。模板的另一条规则是如何在模板中定义标识符, 这是通常的语法:$ identifier, 但你也有$ {identifier}。

这意味着$ {identifier}与$ identifier相同, 但是可以用于以下情形:

word = dict(noun = 'feed')
Template('Please don\'t stop ${noun}ing me').substitute(word)
"Please don't stop feeding me"

让我们看看如何使用alternate()和safe_substitute()。

fact = Template('$alter_ego is weak but wait till he transforms to $superhero!')
fact.substitute(alter_ego='Bruce Banner', superhero='Hulk')
'Bruce Banner is weak but wait till he transforms to Hulk!'
hero = dict(alter_ego='Peter Parker')
fact.substitute(hero)
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

<ipython-input-244-c82f6a2ebc02> in <module>()
      1 hero = dict(alter_ego='Peter Parker')
----> 2 fact.substitute(hero)


~/anaconda3/envs/tensorflow/lib/python3.5/string.py in substitute(*args, **kws)
    127             raise ValueError('Unrecognized named group in pattern', 128                              self.pattern)
--> 129         return self.pattern.sub(convert, self.template)
    130 
    131     def safe_substitute(*args, **kws):


~/anaconda3/envs/tensorflow/lib/python3.5/string.py in convert(mo)
    117             named = mo.group('named') or mo.group('braced')
    118             if named is not None:
--> 119                 val = mapping[named]
    120                 # We use this idiom instead of str() because the latter will
    121                 # fail if val is a Unicode containing non-ASCII characters.


KeyError: 'superhero'

上面的示例将引发错误, 因为未定义超级英雄。但是, 尝试一下…

fact.safe_substitute(hero)
'Peter Parker is weak but wait till he transforms to $superhero!'

safe_substitute()是使用模板的优势之一。

你问为什么会有这么多的字符串格式设置选项?

好吧, 这主要是语法首选项的问题。这通常归结为简单性与冗长性之间的权衡, 并且还取决于你对现有语法的熟悉程度。例如, 对于C语言背景的人们来说, 使用%进行字符串格式化似乎很自然。 Python中的模板易于编写, 而使用format()可能更冗长, 但功能更多。

格式化字符串文字(f字符串)

这是Python版本3.6中添加的另一种字符串格式化方法。格式化的字符串文字或f字符串是前缀为’f’或’F’的字符串文字。你可以在大括号{}中定义要在字符串中使用的标识符。

为什么还有另一个字符串格式化选项?实用性和简单性很美, 这就是原因!

查看以下示例, 以了解为什么f-strings实际上是在Python中格式化字符串最简单实用的方法。

alter_ego =’Peter Parker’超级英雄=’spiderman’f'{alter_ego}很弱, 但请等他转变为{superhero}!”

注意:上面的代码仅适用于Python 3.6及更高版本。要检查已安装的Python版本, 请在终端上键入:python -V。另外, 你还可以在Python中使用sys模块。要使用此功能, 只需执行以下操作:

import sys
sys.version

格式化的字符串实际上是在运行时评估的表达式, 这意味着你可以在f字符串的花括号内使用任何Python表达式, 这是使用f字符串的另一大优势。

f'{alter_ego}很弱, 但要等到他转变为{superhero.capitalize()}!”

F弦还不是很好!但是, 等等, 它变得更好。.与你之前看到的其他三种方法相比, f字符串也更快。这是因为它们被预先解析并存储在有效的字节码中, 以便更快地执行。

拉正确的弦!

恭喜, 你已经完成了本教程的结尾!你已经了解了什么是字符串, 了解了字符串切片, 并了解了可以对字符串执行的一些操作。你还看到了多种格式化字符串的方法。但是请记住, 掌握任何技术的关键是练习!

字符串是Python中几种数据类型之一。查阅srcmini的Data Science的Data Types课程, 以了解有关列表, 字典, 元组和集合的更多信息。在本课程中, 你可以使用对数据类型的了解。你将使用芝加哥市区的运输数据进行数据科学分析。亲自去看看…

赞(0)
未经允许不得转载:srcmini » Python字符串用法教程

评论 抢沙发

评论前必须登录!