字符串

字符串

  • 一个个字符组成的有序的序列,是字符的集合
  • 使用单引号,双引号,三引号引住的字符序列
  • 字符串是不可变对象

 

字符串定义

示例:

s1 = 'string1'
s2 = "string2"
s3 = '''this's is a"string"'''
s4 = 'hello \n world'
s5 = r"hello \n world"
sql = """select * from user where name='tom'"""

 

字符串支持使用索引访问

sql = "select * from user where name='tom'"
sql[4] #字符串c

 

有序的字符集合

str = "hi hi"

for i in str:
    print(i)

输出结果为:

h
i
 
h
i

 

可迭代

str = "hi hi"

l1 = list(str)
print(l1)

输出结果为:

['h', 'i', ' ', 'h', 'i']    

 

字符串join连接

  • “string”.join(iterable) ->str
    • 将可迭代对象连接起来,使用string作为分隔符
    • 可迭代对象本身元素都是字符串
    • 返回一个新字符串

示例:

l1 = ['1','2','3']

print("\"".join(l1)) #分隔符是双引号
print(" ".join(l1))  #分隔符是空格
print("\n".join(l1)) #分隔符是换行

输出结果为

1"2"3
1 2 3
1
2
3

 

字符串+连接

+ -> str

  • 将两个字符串连接在一起
  • 返回一个新字符串

 

示例:

str1 = 'hello'
str2 = 'world'

str3 = str1 + ' '+str2
print(str3)

输出为:

hello world

 

字符串分割

分割字符串的方法有两类

  • split,将字符串按照分隔符分割成若干字符串,并返回列表
  • partition,将字符串按照分隔符分割成2段,返回这2段和分隔符的元祖

 

split(sep=none,maxsplit=-1)->list of strings

  • 从左到右
  • sep指定风格字符串,缺省的情况下用空白字符串作为分隔符
  • maxsplit指定分割次数,-1表示遍历整个字符串

示例:

s1 = "i'm \ta super student."

print(s1.split())
print(s1.split(' '))
print(s1.split('s'))
print(s1.split('super'))
print(s1.split('super '))
print(s1.split(' ',maxsplit=2))
print(s1.split('\t',maxsplit=2))

输出为:

["i'm", 'a', 'super', 'student.']
["i'm", '\ta', 'super', 'student.']
["i'm \ta ", 'uper ', 'tudent.']
["i'm \ta ", ' student.']
["i'm \ta ", 'student.']
["i'm", '\ta', 'super student.']
["i'm ", 'a super student.']

 

rsplit(sep=none,maxsplit=-1)->list of strings

  • 从右向左
  • sep指定分割字符串,缺省的情况下空白字符串作为分隔符
  • maxsplit指定分割次数,-1表示遍历整个字符串

示例:

s1 = "i'm \ta super student."

print(s1.rsplit())
print(s1.rsplit(' '))
print(s1.rsplit('s'))
print(s1.rsplit('super'))
print(s1.rsplit('super '))
print(s1.rsplit(' ',maxsplit=2))
print(s1.rsplit('\t',maxsplit=2))

输出为:

["i'm", 'a', 'super', 'student.']
["i'm", '\ta', 'super', 'student.']
["i'm \ta ", 'uper ', 'tudent.']
["i'm \ta ", ' student.']
["i'm \ta ", 'student.']
["i'm \ta", 'super', 'student.']
["i'm ", 'a super student.']

 

splitlines([keepends])-> list of strings

  • 按照行来分割字符串
  • keepends指的是是否保留行分隔符
  • 行分隔符包括\n \r\n \r等

 

示例:

s1 = 'ab c\n\nde fg\rkl\r\n'
s2 = 'ab c\n\nde fg\rkl\r\n'
s3 = '''i'm a super student.
you're a super teacher.'''

print(s1.splitlines())
print(s2.splitlines(True))
print(s3.splitlines())

输出为:

['ab c', '', 'de fg', 'kl']
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
["i'm a super student.", "you're a super teacher."]

 

partition(sep) ->(head,sep,tail)

  • 从左至右,遇到分隔符就把字符串分割成两部分,返回头,分隔符,尾三部分的三元组,如果没有找到分隔符就返回头,2个空元素的三元组
  • sep分隔字符串,必须制定

 

示例:

s1 = "i'm a super student"

print(s1.partition('s'))
print(s1.partition('stu'))
print(s1.partition(' '))
print(s1.partition('abc'))

输出为;

("i'm a ", 's', 'uper student')
("i'm a super ", 'stu', 'dent')
("i'm", ' ', 'a super student')
("i'm a super student", '', '')

 

rpartition(sep) ->(head,sep,tail)

  • 从右至左,遇到分隔符就把字符串分割成两部分,返回头,分隔符,尾三部分的三元组,如果没有找到分隔符就返回头,2个空元素的三元组
  • sep分隔字符串,必须制定

 

字符串大小写

upper()    全大写

lower()    全小写

swapcase()  交互大小写

 

示例:

s1 = "HELLO world"

print(s1.upper())
print(s1.lower())
print(s1.swapcase())

输出为;

HELLO WORLD
hello world
hello WORLD

 

字符串修改

replace(old,new[,count]) ->str

  • 字符串中找到匹配替换为新子串,返回新字符串
  • count表示替换几次,不制定就是全部替换

示例:

s1 = 'www.google.com'

print(s1.replace('w','p'))
print(s1.replace('w','p',2))
print(s1.replace('w','p',3))
print(s1.replace('ww','p',2))
print(s1.replace('www','python'))

输出为:

ppp.google.com
ppw.google.com
ppp.google.com
pw.google.com
python.google.com

 

strip([chars]) ->str

  • 从字符串两端去除指定的字符集chars中的所有字符
  • 如果chars没有指定,去除两端的空白字符
s1 = "\r \n \t hello world \n \t"
print(s1.strip())
s2 = "i am very very very sorry"
print(s2.strip('iy'))

输出为:

hello world
 am very very very sorr

lstrip([chars]) ->str

  • 从左开始

rstrip([chars]) ->str

  • 从右开始

 

find(sub[,start[,end]]) ->int

在指定区间[start,end),从左向右,查找子串sub,找到返回索引,没找到返回-1

rfind(sub[,start[,end]]) ->int

在指定区间[start,end),从右向左,查找子串sub,找到返回索引,没找到返回-1

示例:

s = "i am very very very sorry"
print(s.find('very'))
print(s.find('very',5))
print(s.find('very',6,13))
print(s.rfind('very',10))
print(s.rfind('very',10,15))
print(s.rfind('very',-10,-1))

输出为:

5
5
-1
15
10
15

 

index(sub,[,start[,end]) ->int

在指定区间[start,end)从左至右,查找子串sub,找到返回索引,没找到抛出异常

rindex(sub,[,start[,end]) ->int

在指定区间[start,end)从右至左,查找子串sub,找到返回索引,没找到抛出异常

示例:

s = "i am very very very sorry"
print(s.index('very'))
print(s.index('very',5))
print(s.index('very',6,13))
print(s.rindex('very',10))
print(s.rindex('very',10,15))
print(s.rindex('very',-10,-1))

输出为:

5
Traceback (most recent call last):
5
  File "E:/PycharmProjects/untitled/test/a.py", line 13, in <module>
    print(s.index('very',6,13))
ValueError: substring not found

 

字符串查找

时间复杂度

  • index和count方法都是O(n)
  • 随着列表数据规模增大,效率下降

len(string)

  • 返回字符串的长度,即字符的个数

count(sub[,start[,end]]) ->int

  • 在指定的区间[start,end)从左至右,统计子串sub出现次数

示例:

s = "i am very very very sorry"
print(s.count('very'))
print(s.count('very',5))
print(s.count('very',10,14))

输出为:

3
3
1

 

endswith(suffix[,start[,end]]) ->bool

  • 在指定的区间[start,end),字符串时候是suffix结尾

startswith(prefix[,start[,end]]) ->bool

  • 在指定的区间[start,end),字符串时候是prefix开头

示例:

s = "i am very very very sorry"
print(s.startswith('very'))
print(s.startswith('very',5))
print(s.startswith('very',5,9))
print(s.endswith('very',5,9))
print(s.endswith('sorry',5))
print(s.endswith('sorry',5,-1))
print(s.endswith('sorry',5,100))

输出为:

False
True
True
True
True
False
True

 

isalnum() -->bool  是否是字母和数字组成

isalpha()  是否是字母

isdecimal()  是否只包含十进制数字

isdigit()  是否全部数字(0-9)

isdentifier()  是不是字母和下划线开头,其他都是字母,数字,下划线

islower()  是否都是小写

isupper()  是否都是大写

isspace()  是否只包含空白字符

 

字符串格式化

printf=-tyle formatting格式

示例:

s1 = "i am %03d"%(20,)
print(s1)
s2 = "i like %s." %'python'
print(s2)
s3 = "i am %-5d"%(20,)
print(s3)

输出为:

i am 020
i like python.
i am 20   

 

format函数格式字符串语法

  • "{}{xxx}".forma(*args,**kwargs) ->str
  • args是位置参数,是一个元祖
  • kwargs是关键字参数,是一个字典
  • 花括号标志占位符
  • {}表示按照顺序匹配位置参数,{n}表示区位置参数索引为N的值
  • {xxx}表示在关键字参数中搜索名称一致的
  • {{}}表示打印花括号

 

位置参数,按照位置顺序用位置参数替换前面的格式字符串的占位符中

示例:

s = "{} {}".format('192.168.1.1',8888)
print(s)

输出为:

192.168.1.1 8888

 

关键字参数,位置参数按需要匹配,关键字参数按照名词匹配

示例:

s = "{server} {1} {0}".format(8888,'192.168.1.1',server="web server info:")
print(s)

输出为:

web server info: 192.168.1.1 8888

 

访问元素

示例:

s = "{0[0]}.{1[1]}".format('hello','world')
print(s)

输出为:

h.o

 

对齐

示例:

s1 = '{0}*{1}={2:<2}'.format(3,2,2*3)
print(s1)
s2 = '{0}*{1}={2:<02}'.format(3,2,2*3)
print(s2)
s3 = '{0}*{1}={2:>02}'.format(3,2,2*3)
print(s3)
s4 = '{:^30}'.format('centerred')
print(s4)
s5 = '{:*^30}'.format('centerred')
print(s5)

输出为:

3*2=6 
3*2=60
3*2=06
          centerred           
**********centerred***********

 

浮点数

示例:

print('{}'.format(3**0.5))     
print('{:g}'.format(3**0.5))
print('{:f}'.format(3**0.5))
print('{:10f}'.format(3**0.5))
print('{:2}'.format(102.231))
print('{:.2}'.format(3**0.5))
print('{:.2f}'.format(3**0.5))
print('{:3.2f}'.format(3**0.5))
print('{:3.3f}'.format(0.2745))
print('{:3.3%}'.format(1/3))    

输出为:

1.7320508075688772
1.73205
1.732051
  1.732051
102.231
1.7
1.73
1.73
0.275
33.333%

 

posted @ 2018-09-14 14:20  rivendare  阅读(185)  评论(0编辑  收藏  举报