1、要访问字符串中的字符,比如最后一个字符,你需要知道它在字符串中的位置。
编号或索引从0到小于字符串长度的1开始。
str='Antarcticaisreallycold.' print('str=',str) #firstcharacter print('str[0]=',str[0]) #lastcharacter print('str[-1]=',str[-1]) #slicing2ndto5thcharacter print('str[1:5]=',str[1:5]) #slicing6thto2ndlastcharacter print('str[5:-2]=',str[5:-2])
2、如果索引从左到右遵循递增顺序模式,则从右到左遵循递减顺序模式。
即从-1、-2、-3.因此,如果您想访问最后一个字符,您可以使用两种方法。
str='Antarcticaisreallycold.' a=len(str) print('lengthofstr',a) #lastcharacterwiththehelpoflengthofthestring print('str[a]',str[a-1]) #lastcharacterwiththehelpofindexing print('str[-1]',str[-1])
以上是python字符串访问字符的方法,希望对大家有所帮助。更多Python学习指导:基础教程python基础教程
本文教程操作环境:windows7系统Python 3.9.1,DELL G3电脑。