美奇科技 发表于 2018-8-12 10:39:56

python内置对象---字符串类型

  字符串是一个有序的字符的集合。
  一、字符串常量
  编写方法:
  单引号:'f"uck'
  双引号:"f'uck"
  三引号:"""fuck""",'''fuck'''
  转义字符:"f\tc\nuc\0k"
  Raw字符串:r"C:\new\test.spm"
  Byte字符串:b'fu\x01uk'
  以下是使用字符串常量表达式创建
  实例    1.单双引号是一样的
  >>> 'fuck',"fuck"
  ('fuck', 'fuck')
  >>> 'fuc"k',"fuc'k"
  ('fuc"k', "fuc'k")
  >>> 'fuc\'k',"fuc\""
  ("fuc'k", 'fuc"')
  2.用转义序列代表特殊字节,每个转义字符代表一个字节
  >>> s='a\tb\nc'
  >>> print(s)
  a       b
  c
  >>> len(s)
  5
  >>>
  >>> s='a\0b\0c'   #\0标识null(零字符),将八进制编码转义为一个数字
  >>> s
  'a\x00b\x00c'
  >>> print(s)
  abc
  3.raw字符串抑制转义
  myfile=open('C:\new\text.txt','w')打开一个文件时,会被\n和\t替换,此处就使用字母r在引号前使用,抑制转义。
  myfile=open(r'C:\new\text.txt','w')
  4.字符串块:三重引号,编程多行文本数据非常便捷。
  >>> s="""fuck
  ... you
  ... you
  ... you
  ... you"""
  >>>
  >>> s
  'fuck\nyou\nyou\nyou\nyou'
  >>> print(s)                            #print的友好格式
  fuck
  you
  you
  you
  you
  >>>
  二、字符串应用
  1.基本操作
  >>> len('abcdef')      #计算字符串长度
  6
  >>> 'abc'+'def'            #合并字符串
  'abcdef'
  >>> 'fuck'*4                #重复打印字符串
  'fuckfuckfuckfuck'
  >>>
  >>> s='fuck'                #定义一个变量x去获取一个序列(这里是字符串)的元素,并对每一个元素执行一个或多个语句操作。
  >>> for x in s:print(x)
  ...
  f
  u
  c
  k
  >>>
  2.索引和分片
  python中字符串是有序的集合,可以通过其位置获得他们的元素,字符串中的字符是通过索引提取的。

  >>> s='fuck'
  >>> s,s[-2]            #正偏移、负偏移,偏移0就是字符串的第一个字符
  ('f', 'c')
  >>> s                #分片,使用冒号分隔字符串,python返回一个新的对象,左边的偏移称下边界(包含下边界在内),右边的偏移称上边界(不包含上边界)。
  'u'                      #以上就是提取包含下边界偏移1,直到不包含上边界偏移2的元素
  >>>
  >>> s[:1]                #下边界默认值为0
  'f'
  >>> s                #上边界默认值为字符串长度
  'uck'
  >>> s[:-1]                #下边界默认值为0,下边界是-1(对应元素的最后一项)
  'fuc'
  >>>
  3.扩展分片
  X在X对象中,从偏移为I直到偏移为J-1,每隔K元素索引一次
  >>> X='123456789'
  >>> X            #提取从偏移值0到8,间隔2个元素的元素
  '147'
  >>>
  >>> Y='hello'
  >>> Y[::-1]            #可以使用负数做步进,进行反转
  'olleh'
  >>>
  4.字符串转换
  >>> int('666')+334      #将字符串转换为数字
  1000
  >>> '666'+str(334)      #将数字转换为字符串
  '666334'
  >>> '666'+repr(334)      #将对象转换为字符串
  '666334'
  >>> ord('a')                  #将单个字符转换为ASCII码
  97
  >>> chr(97)                  #将ASCII码转换为对象的字符
  'a'
  >>> q=ord('12')
  Traceback (most recent call last):
  File &quot;<stdin>&quot;, line 1, in <module>
  TypeError: ord() expected a character, but string of length 2 found            #ord()函数期望是一个字符,但是字符串有2个长度了
  >>>
  5.修改字符串
  字符串是一个有序的不可改变的特性,不可变是不可以在原处修改一个字符串。如
  >>> s=&quot;fuck&quot;
  >>> s=&quot;why&quot;
  Traceback (most recent call last):
  File &quot;<stdin>&quot;, line 1, in <module>
  TypeError: 'str' object does not support item assignment
  >>>
  若想更改字符串内容,可使用合并、分片工具来建立并复制给一个新的字符串对象。
  >>> x='fuck'
  >>> x='fuck'+'u'
  >>> x
  'fucku'
  >>> x=x[:3]+'you'+x
  >>> x
  'fucyouu'
  >>>
  也可以通过replace函数更改字符串内容
  >>> x=&quot;fuck&quot;
  >>> x=x.replace('ck','n')
  >>> x
  'fun'
  >>>
  6.字符串方法(函数)
  除了表达式运算符可以处理字符串外,还可以使用字符串方法,方法调用同时进行2次操作。
  a.属性读取,具有abject.attribute格式的表达式。读取abject对象的attribute属性。
  b.函数调用表达式,调用函数代码,传递零活更多用逗号隔开的参数对象,最后返回函数的返回值。
  1).字符串方法实例:修改字符串
  >>> s=&quot;fuck&quot;
  >>> s=s.replace('ck','n')
  >>> s
  'fun'
  >>> s='xxxfuckxxxfuck'
  >>> where=s.find('fuck')      #find()方法返回子字符串出现的偏移,未找到返回-1
  >>> where
  3
  >>> s=s[:where]+'ooo'+s[(where+3):]
  >>> s
  'xxxoookxxxfuck'
  >>>
  >>> s='fuck'
  >>> L=list(s)      #将字符串打散为一个序列
  >>> L
  ['f', 'u', 'c', 'k']
  >>> L='g'      #更改序列内容
  >>> L='g'
  >>> L
  ['g', 'g', 'c', 'k']
  >>> s=''.join(L)    #通过设定NULL分隔符,join将列表字符串链接在一起
  >>> s
  'ggck'
  >>>
  >>> '000'.join(['f','u','c','k']) #通过设定000分隔符,将列表连接在一起
  'f000u000c000k'
  >>>
  2)字符串方法实例:文本解析
  分析结构并提取字串,为了提取固定偏移的字串,可以利用分片技术:
  >>> s='aaa bbb ccc'
  >>> L1=s[:3]
  >>> L2=
  >>> L2=s                #这组数据出现在固定偏移处,因此可以通过分片从原始字符串分出来,这种技术叫 解析。
  >>> L1
  'aaa'
  >>> L2
  'ccc'
  >>>
  >>> s='aaa bbb ccc'      #此字符串是有空格分隔的
  >>> L1=s.split()                #通过split()方法将一个字符串分隔为一个子字符串列表
  >>> L1
  ['aaa', 'bbb', 'ccc']
  >>>
  >>> s='fuck,u,ha'      #字符串中有,
  >>> L1=s.split(',')            #通过指定分隔符为,
  >>> L1
  ['fuck', 'u', 'ha']
  >>>
  >>> s='aaafuckbbbfuckccc'      #字符串重复出现fuck
  >>> L1=s.split('fuck')                #可以指定分隔符为fuck
  >>> L1
  ['aaa', 'bbb', 'ccc']
  >>>
  3)实际应用中常见的字符串方法
  >>> s='this is a test\n'            #定义一个字符串对象
  >>> s
  'this is a test\n'
  >>> s.rstrip()                  #去除结尾的空行
  'this is a test'
  >>> s.upper()                #转换为大写
  'THIS IS A TEST\n'
  >>> s.endswith('\n')      #测试结尾字符是否为\n
  True
  >>> s.startswith('th')      #测试开始字符是否为th
  True
  >>> s.find('is') != -1            #通过find方法测试变量s中是否存在is子串
  True
  >>> 'is' in s                        #可以通过in测试变量s中是否存在is子串
  True
  >>> str='\n'
  >>> s.endswith(str)      #给endswith()方法传入一个变量str来测试变量s是否存在str的值
  True
  >>> s[-len(str):]==str    #通过len函数测试变量s是否存在str的值
  True
  >>>
  expandtabs用法
  >>> a='name\tglass\tsex\tprogram\nxiaoming\tdgxin\tman\tjishu\nlifeng\tdgxin\tnan\tjishu\nyang\tmme\tnan\tjishu\t'
  >>> v=a.expandtabs(20)    #遇到\t 不足20个字符自动补齐至20个字符
  >>> print(v)
  name                glass               sex               program
  xiaoming          dgxin               man                jishu
  lifeng                dgxin               nan               jishu
  yang               mme                nan               jishu
  >>>
  >>> a='1234'
  >>> a.isdecimal() #判断是否为数字
  True
  >>> a.isdigit()      #判断是否为数字
  True
  >>> a='二'
  >>> a.isdecimal()
  False
  >>> a.isdigit()
  False
  >>> a='②'
  >>> a.isdecimal()
  False
  >>> a.isdigit()
  True
  >>> a=&quot;1 &quot;
  >>> a.isspace()      #判断是否全部为空格
  False
  >>> a=&quot;   &quot;
  >>> a.isspace()
  True
  >>>
  >>> a=&quot;this is a test&quot;
  >>> a.title()                        #转换为标题格式,首字母都大写
  'This Is A Test'
  >>>
  >>> a='this is a test'
  >>> a
  'this is a test'
  >>> b='_'.join(a)            #指定分隔符来分隔字符串中所有字符
  >>> b
  't_h_i_s_ _i_s_ _a_ _t_e_s_t'
  >>>
  >>> a='test'
  >>> a.rstrip()      #去除右边空格
  'test'
  >>> a.lstrip()      #去除左边空格
  'test'
  >>> a.strip()         #去除两端空格
  'test'
  >>>
  >>> a=&quot;\ttest&quot;
  >>> a.strip()                #也可以去除空行和tab
  'test'
  >>> a=&quot;\ntest&quot;
  >>> print(a)
  test
  >>> b=a.strip()
  >>> print(b)
  test
  >>> a='test'
  >>> a.lstrip('t')            #去除左边的t
  'est'
  >>>
  >>> a='test'
  >>> a.lstrip('98yuit')            #会每个字符(应该是子序列)都去匹配对象test。
  'est'
  >>>
  >>> a.lstrip('98yuite')                #匹配到了子序列te
  'st'
  >>>
  >>> s=&quot;this is a test&quot;
  >>> s.partition('s')            #根据s分一次字符串。会保留s
  ('thi', 's', ' is a test')
  >>> s.split('s')                  #根据s分一次或N次字符串(默认全部分隔),会失去s
  ['thi', ' i', ' a te', 't']
  >>> s.split('s',1)
  ['thi', ' is a test']
  >>> s.split('s',2)
  ['thi', ' i', ' a test']
  >>>
  >>> a='this is a test'
  >>> a.startswith('this')      #以什么开头
  True
  >>> a.endswith('st')            #以什么结尾
  True
  >>>
  >>> a='this Is a teST'
  >>> a.swapcase()                #大写转小写,小写转大写
  'THIS iS A TEst'
  >>>
页: [1]
查看完整版本: python内置对象---字符串类型