要在Python中获得一个给定字符串的子串,你可以使用一个流行的功能,叫做 "切片"。其语法是 **string[start:stop:step]**具有如下含义。
**start**是子串中包含的第一个字符的索引。**stop**是最后一个字符的索引,但它本身不包括在子串中,而**step**是步长,允许你在创建子串时跳过一些字符,或者使用负步长从右到左遍历原始字符串。
子串语法示例
下面是一个例子,你应用这个语法从原始字符串'hello world' ,得到子串'hello' 。
>>> s = 'hello world'
>>> s[0:5:1]
'hello'
为了便于理解,这里是字符串的索引表'hello world'- 我用s和e标记了开始和停止的索引。
| h | e | l | l | o | w | o | r | l | d | |
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| s | e |
替代方法
你可以用八种不同的方法来获取一个给定字符串的子串。
它们是这样的。
**string[start:stop:step]**- 获取子串,给定起始和终止索引,以及步长大小**string[start::step]**- 获取子串,但在字符串边界处停止。**string[:stop:step]**- 获取子串,但是以字符串的边界为起点。**string[::step]**- 获取子串,其开始和结束都是默认的字符串边界。**string[start:stop]**- 获取默认步长为1的子串。**string[start:]**- 获取默认步长为1的子串,并在字符串边界处停止。**string[:stop]**- 获取默认在字符串边界开始和停止的子串。**string[::] and string[:]**- 获取原始字符串的副本。
花点时间,慢慢地看完所有的例子,每种方法都要看一遍--这将是提高你的编码技能的好时机
>>> s = 'hello world'
>>> s[0:5:1] # 1
'hello'
>>> s[0::1] # 2
'hello world'
>>> s[:5:2] # 3
'hlo'
>>> s[::2] # 4
'hlowrd'
>>> s[2:5] # 5
'llo'
>>> s[2:] # 6
'llo world'
>>> s[:5] # 7
'hello'
>>> s[::] # 8
'hello world'
接下来让我们深入研究一些实际的例子。
Python 获取两个索引之间的子串
要获得两个索引start (包括的)和stop (不包括的)之间的子串,请使用切分表达式string[start:stop] 。例如,要获得原始字符串中以索引2开始,以索引5结束的子串'hello world' ,使用表达式'hello world'[2:5] 。
start, stop = 2, 5
s = 'hello world'
print(s[2:5])
# llo
Python按长度获取子串
要想通过给定的长度n 和start 索引获得原字符串的子串,使用切片表达式string[start:start+n] 。例如,要获得从索引2开始,长度为5个字符的'hello world' 子串,使用表达式'hello world'[2:2+5] 或'hello world'[2:7] 。
start = 2
n = 5
s = 'hello world'
print(s[start:start+n])
# llo w
Python 获取从索引到结尾的子串
要获得一个具有给定索引的子串start ,并一直向右切分,使用切分表达式string[start:] 。例如,要获得从索引2开始的'hello world' 的子串,使用表达式'hello world'[2:] ,结果是'llo world' 。
start = 2
s = 'hello world'
print(s[start:])
# llo world
Python从一个字符串中获取最后N个字符
要从一个给定的字符串中获得最后的N 字符,使用切片表达式string[-N:] 。例如,要获得'hello world' 的最后5个字符,使用表达式'hello world'[-5:] ,结果是'world' 。
N = 5
s = 'hello world'
print(s[-N:])
# world
Python 从一个字符串中获取每一个其他的字符
要从一个给定的字符串中获得每一个其他的字符,使用切片表达式string[::2] ,设置步长为2。例如,要获得'hello world' 的每一个其他字符,使用表达式'hello world'[::2] ,结果是'hlowrd' 。
s = 'hello world'
print(s[::2])
# hlowrd
切片的视频解释
如果你需要深入解释切分的工作原理,请随时查看我的视频指南。
从哪里开始?
理论够多了,让我们来练习一下吧!
要想在编码方面取得成功,你需要走出去,为真正的人解决真正的问题。这样你才能轻松成为六位数的收入者。而这也是你如何在实践中打磨出你真正需要的技能。毕竟,学习没有人需要的理论有什么用?
实践项目就是你在编码中磨练你的锯子的方法!
你想通过专注于实际的代码项目,成为一个代码大师,真正为你挣钱,为人们解决问题吗?
那就成为Python的自由开发者吧!这是接近提高Python技能任务的最佳方式--即使你是一个完全的初学者。
参加我的免费网络研讨会"如何建立你的高收入技能Python",看看我是如何在网上发展我的编码业务的,你也可以这样做--从你自己家里的舒适度。
The postHow to Get the Substring of a String in Python?first appeared onFinxter.