如何在 Python 中获取字符串的子字符串? [英] How do I get a substring of a string in Python?

查看:82
本文介绍了如何在 Python 中获取字符串的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 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?

也许像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?

推荐答案

>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'

Python 将这个概念称为切片",它不仅仅适用于字符串.在此处查看全面介绍.

Python calls this concept "slicing" and it works on more than just strings. Take a look here for a comprehensive introduction.

这篇关于如何在 Python 中获取字符串的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆