>>>a = '0123456789'
>>>b = a[0:3] # 截取第一位到第三位的字符
>>>b
'012'
>>>b = a[:] # 截取字符串的全部字符
>>>b
'0123456789'
>>>b = a[6:] # 截取第七个字符到结尾
>>>b
'6789'
>>>b = a[:-3] # 截取从头开始到倒数第三个字符之前
>>>b
'0123456'
>>>b = a[2] # 截取第三个字符
>>>b
'2'
>>>b = a[-1] # 截取倒数第一个字符
>>>b
'9'
>>>b = a[::-1] # 创造一个与原字符串顺序相反的字符串
>>>b
'9876543210'
>>>b = a[-3:-1] # 截取倒数第三位与倒数第一位之前的字符
>>>b
'78'
>>>b = a[-3:] # 截取倒数第三位到结尾
>>>b
'789'
转载请注明:八度生活 » python截取字符串