我想从第三个字符到字符串末尾获得一个新字符串,例如myString[2:end]。如果省略第二部分意味着“到结尾”,如果省略第一部分,它是否从头开始?
当前回答
a="Helloo"
print(a[:-1])
在上面的代码中,[:-1]声明从开始打印到最大限制-1。
输出:
>>> Hello
注意:这里a[:-1]也与a[0:-1]和a[0:len(a)-1]相同
a="I Am Siva"
print(a[2:])
输出:
>>> Am Siva
在上面的代码中,[2:]声明从索引2打印到最后一个元素。
请记住,如果您将打印字符串的最大限制设置为(x),那么它将打印字符串直到(x-1),并且还请记住列表或字符串的索引将始终从0开始。
其他回答
text = "StackOverflow"
#using python slicing, you can get different subsets of the above string
#reverse of the string
text[::-1] # 'wolfrevOkcatS'
#fist five characters
text[:5] # Stack'
#last five characters
text[-5:] # 'rflow'
#3rd character to the fifth character
text[2:5] # 'rflow'
#characters at even positions
text[1::2] # 'tcOefo'
>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'
Python将这一概念称为“切片”,它不仅仅适用于字符串。请在此处查看全面介绍。
Subs()通常(即PHP和Perl)是这样工作的:
s = Substr(s, beginning, LENGTH)
所以参数是开始和长度。
但Python的行为不同;它需要开头和END(!)之后的一个。初学者很难发现这一点。因此,Substr(s,begin,LENGTH)的正确替换为
s = s[ beginning : beginning + LENGTH]
为了完整性,其他人没有提到过。数组切片的第三个参数是一个步骤。因此,反转字符串非常简单:
some_string[::-1]
或者选择其他字符:
"H-e-l-l-o- -W-o-r-l-d"[::2] # outputs "Hello World"
在字符串中前后移动的能力与从开始或结束排列切片的能力保持一致。
str1='There you are'
>>> str1[:]
'There you are'
>>> str1[1:]
'here you are'
#To print alternate characters skipping one element in between
>>> str1[::2]
'Teeyuae'
#To print last element of last two elements
>>> str1[:-2:-1]
'e'
#Similarly
>>> str1[:-2:-1]
'e'
#Using slice datatype
>>> str1='There you are'
>>> s1=slice(2,6)
>>> str1[s1]
'ere '
推荐文章
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字