Python String Slicing
Strings and Character Data in Python
String Slicing
Python also allows a form of indexing syntax that extracts substrings from a string, known as string slicing. If s
is a string, an expression of the form s[m:n]
returns the portion of s
starting with position m
, and up to but not including position n
:
s = 'foobar'
s[2:5]
#'oba'
Remember: String indices are zero-based. The first character in a string has index 0
. This applies to both standard indexing and slicing.
Again, the second index specifies the first character that is not included in the result—the character 'r'
(s[5]
) in the example above. That may seem slightly unintuitive, but it produces this result which makes sense: the expression s[m:n]
will return a substring that is n - m
characters in length, in this case, 5 - 2 = 3
.
If you omit the first index, the slice starts at the beginning of the string. Thus, s[:m]
and s[0:m]
are equivalent:
Similarly, if you omit the second index as in s[n:]
, the slice extends from the first index through the end of the string. This is a nice, concise alternative to the more cumbersome s[n:len(s)]
:
For any string s
and any integer n
(0 ≤ n ≤ len(s)
), s[:n] + s[n:]
will be equal to s
:
If the first index in a slice is greater than or equal to the second index, Python returns an empty string. This is yet another obfuscated way to generate an empty string, in case you were looking for one:
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2015-11-12 解决 “无法安装 Visual Studio 2010 Service Pack 1,因为此计算机的状态不支持”
2015-11-12 VS2012 professional和VS2012 Ultimate的区别
2014-11-12 sqlite的bool字段