Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

python - 如何在Python中获取字符串的子字符串?(How do I get a substring of a string in Python?)

Is there a way to substring a string in Python, to get a new string from the third character to the end of the string?

(有没有一种方法可以在Python中为字符串加上字符串,以从第三个字符到字符串的末尾获取新的字符串?)

Maybe like myString[2:end] ?

(也许像myString[2:end] ?)

If leaving the second part means 'till the end', and if you leave the first part, does it start from the start?

(如果离开第二部分意味着“直到最后”,而如果离开第一部分,它是否从头开始?)

  ask by Joan Venge translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'

Python calls this concept "slicing" and it works on more than just strings.

(Python称这个概念为“切片”,它不仅适用于字符串,还适用于更多的领域。)

Take a look here for a comprehensive introduction.

(在这里查看全面介绍。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...