Python学习笔记:数据类型 - 字符串类型

【1】序列操作(Sequence Operations:支持按照位置访问其元素)

  1. 字符串是以成对的单引号’或者双引号"包裹在内包含0个或多个字符、数字的对象。
  2. 字符串属于序列类型,支持按照位置顺序访问其元素。
In [1]: s = 'Hello'

In [2]: len(s) # 字符串长度
Out[2]: 5

In [3]: s[0], s[1], s[2], s[3], s[4] # 按位置访问元素
Out[3]: ('H', 'e', 'l', 'l', 'o')

In [4]: s[-1] # s字符串的最后一个字符
Out[4]: 'o'

In [5]: s[len(s)-1] # s字符串的最后一个字符
Out[5]: 'o'

In [6]: s[:3] # 字符串s的切片,从偏移量(offset)0到2,不包括3.
Out[6]: 'Hel'

In [7]: s[1:3] # 字符串s的切片,从偏移量1到2,不包括3.
Out[7]: 'el'

In [8]: s[1:] # 字符串s的切片,从偏移量1到最后一个字符,不包括0.
Out[8]: 'ello'

In [9]: s[:] # 字符串s的切片,从偏移量0到最后一个字符,即:所有字符。
Out[9]: 'Hello'

In [10]: s[0:5:2] # 字符串s的切片,从偏移量0到最后一个字符,步长为2,即:每2个字符取1个,s[0],s[2],s[4]。
Out[10]: 'Hlo'

In [11]: s[::2] # 字符串s的切片,从偏移量0到最后一个字符,步长为2,即:每2个字符取1个,s[0],s[2],s[4]。
Out[11]: 'Hlo'

In [12]: s[:-1] # s[0:len(s)-1],即:s[0:4]
Out[12]: 'Hell'

In [13]: s[0:-1] # s[0:len(s)-1],即:s[0:4]
Out[13]: 'Hell'

In [14]: s[0:] # s[0:len(s)],即:s[0:5]
Out[14]: 'Hello'

In [15]: s[:] # s[0:len(s)],即:s[0:5]
Out[15]: 'Hello'

说明:

  1. 切片中,左界默认值为0。
  2. 切片中,右界默认值为字符串的长度。
  3. 切片中,步长默认值为1。

【2】不可变性(Immutability:元素不可赋值)

字符串是不可变序列,其元素不可被修改。

In [1]: s = 'Hello'

In [2]: s[0] = 'h' # 报错:TypeError,str字符串对象不支持元素赋值。
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-28afdf8ed541> in <module>
----> 1 s[0] = 'h'

TypeError: 'str' object does not support item assignment

【3】操作符

操作符说明
+字符串连接操作
*字符串重复操作
In [3]: s + ', world!'
Out[3]: 'Hello, world!'

In [4]: 'H' * 5 # 'H'重复5遍
Out[4]: 'HHHHH'

In [5]: s * 3 # s引用的字符串重复3遍
Out[5]: 'HelloHelloHello'

【4】类型特有的方法(Type-Specific Methods)

【4.1】查找函数(find, rfind)

  1. find函数:在指定切片中查找sub字符串,返回找到的最小索引号。失败,返回-1。
  2. rfind函数:在指定切片中查找sub字符串,返回找到的最大索引号。失败,返回-1。

示例:

In [1]: s = 'Hello'

In [2]: s.find('l') # 在s字符串中查找'l',分别在2和3的位置找到,返回最小位置索引号2。
Out[2]: 2

In [3]: s.find('W') # 在s字符串中查找'W',未找到,返回-1。
Out[3]: -1

In [4]: s.rfind('l') # 在s字符串中查找'l',分别在2和3的位置找到,返回最大位置索引号2。
Out[4]: 3

函数定义:

    def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.find(sub[, start[, end]]) -> int
        
        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
        
        Return -1 on failure.
        """
        return 0

【4.2】替换函数(replace)

在字符串中用一个字符串代替另外一个。

示例:

In [1]: s = 'Hello'

In [2]: s.replace('e', 'o') # 将字符串s中的所有'e'替换为'o'
Out[2]: 'Hollo'

In [3]: s.replace('l', 'e') # 将字符串s中的所有'l'替换为'o'。
Out[3]: 'Heeeo'

函数定义:

    def replace(self, *args, **kwargs): # real signature unknown
        """
        Return a copy with all occurrences of substring old replaced by new.
        
          count
            Maximum number of occurrences to replace.
            -1 (the default value) means replace all occurrences.
        
        If the optional argument count is given, only the first count occurrences are
        replaced.
        """
        pass

【4.3】转换为大写字母(upper)

In [1]: 'Hello'.upper()
Out[1]: 'HELLO'

【4.4】转换为小写字母(lower)

In [1]: 'Hello'.lower()
Out[1]: 'hello'

【4.5】转换为每个单词首字母大写(title)

In [1]: 'Hello, world.'.title()
Out[1]: 'Hello, World.'

【4.6】分割字符串(split)

split函数:分割字符串。不带参数,默认用空白符分割;否则,用指定字符分割。

示例:

In [30]: 'Hello, world.'.split() # 用空白符(包括空格、制表符)分割字符串,分割后的两个字符串为'Hello,'与'world.'
Out[30]: ['Hello,', 'world.']

In [31]: 'Hello, world.'.split(',') # 用逗号','分割字符串,分割后的两个字符串为'Hello'与' world.'
Out[31]: ['Hello', ' world.']

函数定义:

    def rsplit(self, *args, **kwargs): # real signature unknown
        """
        Return a list of the words in the string, using sep as the delimiter string.
        
          sep
            The delimiter according which to split the string.
            None (the default value) means split according to any whitespace,
            and discard empty strings from the result.
          maxsplit
            Maximum number of splits to do.
            -1 (the default value) means no limit.
        
        Splits are done starting at the end of the string and working to the front.
        """
        pass
    def split(self, *args, **kwargs): # real signature unknown
        """
        Return a list of the words in the string, using sep as the delimiter string.
        
          sep
            The delimiter according which to split the string.
            None (the default value) means split according to any whitespace,
            and discard empty strings from the result.
          maxsplit
            Maximum number of splits to do.
            -1 (the default value) means no limit.
        """
        pass

【4.7】格式化(format)

In [1]: from math import pi # 从math模块导入pi

In [2]: '{:.2f}'.format(pi) # 保留小数点后2位对pi格式化
Out[2]: '3.14'

In [3]: '{:,.2f}'.format(pi*1000) # 带千分位病保留小数点后2位对pi*1000格式化
Out[3]: '3,141.59'

函数定义:

    def format(self, *args, **kwargs): # known special case of str.format
        """
        S.format(*args, **kwargs) -> str
        
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass

【4.8】删除首尾空白字符(strip)

空白字符(whitespace)包括:空格(space)、制表符(tab)、回车符(\r)、换行符(\n)

In [1]: s = ' Hello!' # 第一个字符为空格,调用strip函数后,串首空格字符删除

In [2]: s.strip()
Out[2]: 'Hello!'

In [3]: s = ''.join(['\t', ' Hello! ', '\n'])

In [4]: s
Out[4]: '\t Hello! \n'

In [5]: s.strip()
Out[5]: 'Hello!'

In [6]: s = ''.join(['\t', ' Hello! ', '\r\n'])

In [7]: s
Out[7]: '\t Hello! \r\n'

In [8]: s.strip()
Out[8]: 'Hello!'
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值