詹惠儿

2018-11-12   阅读量: 665

数据分析师 Python编程 Python数据分析

Python中的字符串操作

扫码加入数据分析学习群

概述


字符串是按顺序排列的字符列表。 一个字符是你可以在键盘上键入的任何键。 字符串可以有空格,如:“hello world”。 空字符串是一个包含0个字符的字符串。

Python字符串是不可变的, Python将所有用引号分隔的字符串识别为字符串 (“ “ 要么 ' ')。

字符串操作


要操纵字符串,我们可以使用一些Pythons内置方法。

word = "Hello World"

>>> print word
Hello World

1. 访问
使用[]访问字符串中的字符

word = "Hello World"
letter=word[0]

>>> print letter
H

2. 字符长度

word = "Hello World"

>>> len(word)
11

3. 查找

word = "Hello World"

>>> print word.count('l') # count how many times l is in the string
3

>>> print word.find("H") # find the word H in the string
0

>>> print word.index("World") # find the letters World in the string
6

4. 计数

s = "Count, the number of spaces" >>> print s.count(' ')

8

5. 切片


使用[#:#]获取一组字母
请记住,python,和许多其他语言一样,从0开始算!

print word[0] #get one char of the word
print word[0:1] #get one char of the word (same as above)
print word[0:3] #get the first three char
print word[:3] #get the first three char
print word[-3:] #get the last three char
print word[3:] #get all but the three first char
print word[:-3] #get all but the three last characterword = "Hello World"

word[start:end] # items start through end-1
word[start:] # items start through the rest of the list
word[:end] # items from the beginning through end-1
word[:] # a copy of the whole list测试

Python中的字符串可以测试真值

返回类型将为布尔值(True或False)

word = "Hello World"

word.isalnum()#check如果所有char都是字母数字

word.isalpha()#check如果字符串中的所有字符都是字母
word.isdigit()#test如果字符串包含数字
word.istitle()#test如果字符串包含标题词
word.isupper()#test如果string包含大写
word.islower()#test如果string包含小写
word.isspace()#test如果string包含空格
word.endswith('d')#test if string是否以ad结尾
word.startswith('H')#test if string是否以H开头


		
添加CDA认证专家【维克多阿涛】,微信号:【cdashijiazhuang】,提供数据分析指导及CDA考试秘籍。已助千人通过CDA数字化人才认证。欢迎交流,共同成长!
0.0000 0 0 关注作者 收藏

评论(0)


暂无数据

推荐课程

推荐帖子