Python的字符串切片及常用方法

2017-04-06  本文已影响5793人  忽如寄

获取Python字符串中的某字符可以使用索引:

lang = 'python'
lang[0]
# p
lang[3]
# h

截取字符串中的一段字符串可以使用切片,切片在方括号中使用冒号:来分隔需要截取的首尾字符串的索引,方式是包括开头,不包括结尾

lang[1:4]
# yth

当尾索引没有给出时,默认截取到字符串的末尾

lang[1:]
# ython

当头索引没有给出的时候默认从字符串开头开始截取

lang[:3]
# pyt

当尾索引和头索引都没有给出的时候,默认返回整个字符串,不过这只是一个浅拷贝

lang[:]
# python

当尾索引大于总的字符串长度时,默认只截取到字符串末尾,很明显使用这种方法来截取一段到字符串末尾的子字符串是非常不明智的,应该是不给出尾索引才是最佳实践

lang[3:100]
# hon

当头索引为负数时,则是指从字符串的尾部开始计数,最末尾的字符记为-1,以此类推,因此此时应该注意尾索引的值,尾索引同样可以为负数,如果尾索引的值指明的字符串位置小于或等于头索引,此时返回的就是空字符串

lang[-2:]
# on
lang[-2,2]
# ''

切片是Python中截取字符串最强大的功能。

以下列举部分Python字符串常用的方法:

len(lang)
# 6
'p' in lang
# True
'ab' in lang
# False
max(lang)
# y
min(lang)
# h
lang * 2
# pythonpython
lang2 = 'qython'
lang3 = 'pythoa'

cmp(lang, lang2)
# -1
cmp(lang, lang3)
# 1
cmp(lang, lang)
# 0
chr(97)
# a
ord('a')
# 97
num = 3.14
str(num)
# 3.14
'python'.capitalize()
# Python
'hello world'.split(' ')
# ['hello', 'world']
' hello '.strip()
# hello
' hello '.lstrip()
# 'hello '
' hello '.rstrip()
# ' hello' 
lang.upper()
# PYTHON
lang.lower()
# python
'ABC'.isupper()
# True
'Abc'.islower()
# False
'Hello World'.istitle()
# True
'I am A Boy'.istitle()
# False
'Abc'.swapcase()
# aBC
a = 'hello world'.split()
'-'.join(a)
# hello-world
'hello world'.find('llo')
# 2
'hello world'.find('lloe')
# -1
'hello'.startswith('he')
# True
'hello'.endswith('lle')
# False
a = lang[::-1]
# nohtyp
lang = 'aaa111223'
lang.count('a')
# 3
lang.index('a')
# 0
lang.index('1')
# 3
上一篇 下一篇

猜你喜欢

热点阅读