首页 > 编程知识 正文

python获取字符串某段,python字符串截取函数

时间:2023-05-06 18:31:33 阅读:127879 作者:2468

python字符串切片

pythonstringsupportsslicingtocreatesubstring.notethatpythonstringisimmutable,slicingcreatesanewsubstringfromthesourcestrcestrinstringtriourintiourior

Python字符串支持切片并创建子字符串。 请注意,Python字符串是不变的,切片基于源字符串创建新的子字符串,而原始字符串保持不变。

Python切片字符串(Python slice string )。

Python slice string syntax is:

Python slice字符串语法如下:

str _ object [ start _ pos : end _ pos : step ]

theslicingstartswiththestart _ posindex (已包含) andendsatend_posindex (已排除).thestepparameterisusedtospecifyted )

切片以start_pos索引(包括)开始,以end_pos索引)结束。 使用step参数指定从开始到结束执行索引的步骤。

pythonstringslicingalwaysfollowsthisrule : s [ : I ] s [ I : ]==sforanyindex‘I’。

Python字符串切片始终遵循以下规则: s [:i] s [i:]==s用于任何索引' I '。

alltheseparametersareoptionalstart _ posdefaultvalueis 0,the end _ posdefaultvalueisthelengthofstringandstepdefaultvalueieieistthaltvalueieieieiion

这些参数都是可选的。 - start_pos的默认值为0,end_pos的默认值为字符串长度,step的默认值为1。

let’slookatsomesimpleexamplesofstringslicefunctiontocreatesubstring。

让我们看一个创建子字符串的字符串切片函数的简单示例。

s='HelloWorld '

打印(s [ : ]

print(s[:3360]

Output:

输出:

职业介绍所世界

职业介绍所世界

notethatsincenoneoftheslicingparameterswereprovided,thesubstringisequaltotheoriginalstring。

请注意,子字符串与原始字符串相等,因为没有指定切片参数。

let’slookatsomemoreexamplesofslicingastring。

看看切片字符串的例子。

s='HelloWorld '

first_five_chars=s[:5]

打印(first _ five _ chars ) )。

third _ to _ fifth _ chars=s [ 2:5 ]

打印(third _ to _ fifth _ chars )。

Output:

输出:

你好

llo

Note that index value starts from 0,so start _ pos2referstothethirdcharacterinthestring。

因为索引值从0开始,所以start_pos 2引用字符串中的第三个字符。

使用切片反转字符串(Reverse a String using Slicing ) )。

wecanreverseastringusingslicingbyprovidingthestepvalueas-1。

如果将步长值设置为-1,则可以使用切片反转字符串。

s='HelloWorld '

reverse_str=s[:-1]

print(reverse_str )是

Output: dlroWolleH

输出: dlroWolleH

let’slookatsomeotherexamplesofusingstepsandnegativeindexvalues。

让我们看看使用步骤和负索引值的其他示例。

s1=s[2:8:2]

打印(S1 )。

Output: loo

输出: loo

herethesubstringcontainscharactersfromindexes 2,4 and6。

此处的子字符串包含来自索引2、4和6的字符。

s1=s[8:1:-1]

打印(S1 )。

Output: lroWoll

输出: lroWoll

heretheindexvaluesaretakenfromendtostart.thesubstringismadefromindexes 1to7 fromendtostart。

这里的索引值从头到尾。 子字符串自始至终由索引1到7组成。

s1=s[8:1:-2]

打印(S1 )。

Output: lool

输出: lool

pythonsliceworkswithnegativeindexestoo,in that case,thestart _ posisexcludedandend _ posisincludedinthesubstring。

Python slice还可以使用负索引。 在这种情况下,start_pos被排除,子字符串包含end_pos。

s1=s[-4:-2]

打印(S1 )。

Output: or

输出: or

pythonstringslicinghandlesoutofrangeindexesgracefully。

Python字符串切片成功处理超出范围的索引。

s='Python '

s[100:]

''

s[2:50]

“thon”

that’sallforpythonstringslicefunctiontocreatesubstring。

这就是python字符串切片函数创建的所有子字符串。

千兆存储库。

从GitHub存储库中签出完整的python脚本和其他python示例。

从3:https://www.journal dev.com/23584/python-slice-string翻译

python字符串切片

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。