您的位置:首页 > 编程语言 > Python开发

Python数据类型方法简介一————字符串

2017-06-20 20:08 846 查看
符串是Python中的重要的数据类型之一,并且字符串是不可修改的。字符串的所有修改方法都是修改的副本。
字符串就是引号(单、双和三引号)之间的字符集合。(字符串必须在引号之内,引号必须成对)注:单、双和三引号在使用上并无太大的区别; 引号之间可以采取交叉使用的方式避免过多转义; 单、双引号实现换行必须使用续行符,而三引号可直接续行不必使用续行符号。一、创建字符串
str1='hello world'
二、访问字符串字符串通过索引值来访问字符的,索引值重0开始
str1[2]
'l'
str1[-1]
'd'
str1[0]
'h'
如果访问时超出索引值会报一个indexError异常。
str1[33]
Traceback (most recent call last):
Python Shell, prompt 29, line 1
IndexError: string index out of range
三、切片

字符串的切片即访问字符串中连续的子字符串。切片时只包括起始位置,不包括结束位置。
str1[1:5]
'ello'
str1[1:-1]
'ello worl'
str1[0:-1]
'hello worl'
str1[:]
'hello world'
如果切片时起始位置超出索引范围,会返回一个空字符串。
str1[33:]
''
四、字符串方法

a. count,统计字符或子字符串在字符串中出现的次数格式:S.count(sub[, start[, end]]) -> int sub 是字符串中要查询的子字符串 start是开始统计的索引位置 end是结束的索引位置 返回一个数字
>>> s="hello python"
>>>  s.count('l')
>>>  2
>>> s
'hello python'
>>> s.count('o')
2
>>> s.count('o',4,6)
1
b. capitalize 首字母大写格式:S.capitalize() -> string
>>> s
'hello python'
>>> s.capitalize()
'Hello python'
c.isalnum,isalpha,isdigit,islower,isspace,istitle,isupper这些都是判断字符串里的字符类型,返回的是布尔值。以isdigit判断字符串是否只含有数字格式:S.isdigit() -> boo
>>> s
'hello python'
>>> s.isdigit()
False
>>> s='hello python 1'
>>> s.isdigit()
False
>>> s='123'
>>> s.isdigit()
True
islower判断字符串中的字母是否都是小写字母格式:S.islower() -> bool
>>> s
'hello python'
>>> s.islower()
True
>>> s="Hello python"
>>> s.islower()
False
d. lower/upoer/title把字符串中的字母都变成小写/大写/首字母大写格式:S.lower() -> string S.upper() -> string S.title() -> string
>>> s
'Hello python'
>>> s.lower()
'hello python'
>>> s.upper()
'HELLO PYTHON'
>>> s.title()
'Hello Python'
e. startswith/endswith是否以什么开头/结尾,返回布尔值格式:S.startswith(prefix[, start[, end]]) -> bool S.endswith(suffix[, start[, end]]) -> boolprefix/suffix开头/结尾 start开始的索引位置 end开始的索引位置 返回布尔值
>>> s
'hello python'
>>> s.startswith('he')
True
>>> s.startswith('e')
False
>>> s.startswith('he',4,8)
False
f. replace字符串替换格式:S.replace(old, new[, count]) -> stringold被替换的字符串 new要替换的字符串 count替换的次数 返回一个字符串
>>> s
'hello python'
>>> s.replace('e','E')
'hEllo python'
>>> s.replace('l','L',)
'heLLo python'
>>> s.replace('l','L',1)
'heLlo python'
g. split/rsplit(从右开始)字符串切割格式:S.split([sep [,maxsplit]]) -> list of strings S.rsplit([sep [,maxsplit]]) -> list of stringssep 指定切割字符 maxsplit 最多切割的次数 返回一个以字符串为元素的列表
>>> s
'hello python'
>>> s.split(" ")
['hello', 'python']
>>> s.split("l",1)
['he', 'lo python']
>>> s.rsplit("l",1)
['hel', 'o python']

h. jion 将可迭代的数据类型转换成一个字符串格式:S.join(iterable) -> string
>>> s
'hello python'
>>> S=s.split(" ")
>>> S
['hello', 'python']
>>> " ".join(S)
'hello python'
i. strip去除字符串指定的首尾字符(单个字符为单位匹配)格式:S.strip([chars]) -> string or unicode
>>> s
'hello python'
>>> s.strip("o")
'hello python'
>>> s.strip("n")
'hello pytho'
>>> s='hello olleh'
>>> s.strip("he")
'llo oll'
>>> s.strip("he")
'llo olleh '
strip这个用法是以字符为单位进行匹配,以最后一个例子,要去除he,当前面匹配到l,不在he中结束,后面匹配到空格,空格不在he中,结束。j. find查找指定字符的位置,没有则返回1。找到第一个匹配的字符就返回索引值格式:S.find(sub [,start [,end]]) -> intsub 指定的字符 start开始的索引位置,end结束的索引位置。 返回数字
>>> s='hello python'
>>> s.find('o')
4
>>> s.find('o',5,11)
10
>>> s.find('a')
-1
k. index查找字符所在索引位置,没有报一个异常格式:S.index(sub [,start [,end]]) -> int
>>> s
'hello python'
>>> s.index('h')
0
>>> s.index('h',5)
9
>>> s.index('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
l. format字符串格式化格式:S.format(*args, **kwargs) -> stringargs 参数,指定是位置传参, kwargs 关键字传参
>>> print "my name is {},my age is {}".format('xiaoming',10)
my name is xiaoming,my age is 10
在Python2.6中必须指定参数的位置
>>> print "my name is {0},my age is {1}".format('xiaoming',10)
my name is xiaoming,my age is 10
还有一种方式:
>>> print "my name is %s,my age is %d"%('xiaoming',10)
my name is xiaoming,my age is 10
%s指定数据为字符串,%d指定是数字这两种格式化字符串在Python中常用到五、字符串连接:字符串连接方法有三种,字符串的加法与join方法效果一致,但是原理不同,因为python中字符串是不可变的类型,使用 + 连接两个字符串时会生成一个新的字符串,生成新的字符串就需要重新申请内存,当连续相加的字符串很多时(a+b+c+d+e+f+...) ,效率低下就是必然的了。jion方法使用略复杂,但对多个字符进行连接时效率高,只会有一次内存的申请。这种方法中jion必须是一个可迭代的类型,当然也可以使用字符串格式化的方法进行字符串连接。字符串加法
>>> "hello"+"python"
'hellopython'
字符串的join方法
>>> " ".join(["hello","python"])
'hello python
字符串格式化
>>> "%s%s%s"%('hello',' ','python')
'hello python'
字符串乘法
字符串乘法经常用来打印分隔符。
>>> print "="*10
==========
>>> print "python "*10
python python python python python python python python python python
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息