zoukankan      html  css  js  c++  java
  • python 字符串常用操作方法

    python 字符串常用操作方法

    python 字符串操作常用操作,如字符串的替换、删除、截取、赋值、连接、比较、查找、分割等

    1、去除空格

    str.strip():删除字符串两边的指定字符,括号的写入指定字符,默认为空格

    >>> 'hello'.strip('h')
    'ello'
    >>> '  hello  '.strip()
    'hello'
    >>>

    str.lstrip():删除字符串左边的指定字符,括号的写入指定字符,默认空格

    str.rstrip():删除字符串右边的指定字符,括号的写入指定字符,默认空格

    >>> '  helloe  '.lstrip()
    'helloe  '
    >>> '  hello  '.rstrip()
    '  hello'
    >>>

    2、复制字符串

    关于字符串复制有很多细节,这里不展开,需要用到时,可以去查找资料了解

    3、连接字符串

    3.1 +连接字符串

     注:此方法又称为 "万恶的加号",因为使用加号连接2个字符串会调用静态函数string_concat(register PyStringObject *a ,register PyObject * b),在这个函数中会开辟一块大小
    是a+b的内存的和的存储单元,然后将a,b字符串拷贝进去。如果是n个字符串相连 那么会开辟n-1次内存,是非常耗费资源的。
    >>> a='Hello'+' World'
    >>> a
    'Hello World'
    >>>

    3.2 Python join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。

    语法:str.join(sequence)

    参数

    • sequence -- 要连接的元素序列。

    返回值

    返回通过指定字符连接序列中元素后生成的新字符串。

    >>> s1='-'
    >>> s2=''
    >>> seq = ("r", "u", "n", "o", "o", "b")
    >>> s1.join(seq)
    'r-u-n-o-o-b'
    >>> s2.join(seq)
    'runoob'

    4、查找字符串

    #str.index 和str.find 功能相同,区别在于find()查找失败会返回-1,不会影响程序运行。一般用find!=-1或者find>-1来作为判断条件。
    #str.index:检测字符串中是否包含子字符串str,可指定范围
    #index 用法
    >>> a='hello world' >>> a.index('e') 1 >>> a.index('l',3,6) 3 >>> a.index('x') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found
    >>> b='good boy'
    >>> b.find('g')
    0
    >>> b.find('x')
    -1
    >>> b.find('o',2,5)
    2
    >>>

    5.比较字符串

    str.cmp:比较两个对象,并根据结果返回一个整数。X< Y,返回值是负数 ,X>Y 返回的值为正数。
    #python3已经没有该方法,官方文档是这么写的:
    The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)
    大意就是cmp()函数已经“离开”了,如果你真的需要cmp()函数,你可以用表达式(a > b) - (a < b)代替cmp(a,b)

    python 3.4.3 的版本中已经没有cmp函数,被operator模块代替,在交互模式下使用时,需要导入模块。import operator

    
    

    operator模块的功能如下:

    函数 含义

    operator.lt(a, b)                   a < b
    operator.le(a, b)                  a <= b
    operator.eq(a, b)                 a == b
    operator.ne(a, b)                  a != b
    operator.gt(a, b)                   a > b
    operator.ge(a, b)                  a >= b

    
    
    >>> operator.lt('a','b')
    True
    >>> operator.lt('ab','a')
    False
    >>> operator.le('ca','b')
    False
    >>> operator.gt('bc','b')
    True
    >>>
    
    

    6.是否包含指定字符串 in /not in

    
    
    >>> a='hello world'
    >>> 'hello' in a
    True
    >>> '123' not in a
    True
    >>>
    
    

    7.字符串长度  str.len()

    >>> a='hello world'
    >>> len(a)
    11

    8、字符串中字母大小写转换

    #转换为小写
    >>> a='HELLO WORLD'
    >>> a.lower()
    'hello world'
    #转换为大写
    >>> a='hello world'
    >>> a.upper()
    'HELLO WORLD'
    #大小写互换
    >>> a='hELLO wORLD'
    >>> a.swapcase()
    'Hello World'
    #首字母大写
    >>> a='hello world'
    >>> a.capitalize()
    'Hello world'

    9.将字符串放入中心位置可指定长度以及位置两边字符

    >>> a='hello world'
    >>> a.center(50,'*')
    '*******************hello world********************'
    >>> a.center(50,'-')
    '-------------------hello world--------------------'

    10.字符串统计

    >>> a='hello world'
    >>> print(a.count('o'),a.count('l'))
    2 3

    11.字符串的测试、判断函数,这一类函数在string模块中没有,这些函数返回的都是bool值

    
    
    1 S.startswith(prefix[,start[,end]])  #是否以prefix开头 
    2 S.endswith(suffix[,start[,end]])     #以suffix结尾 
    3 S.isalnum()                             #是否全是字母和数字,并至少有一个字符 
    4 S.isalpha()                          #是否全是字母,并至少有一个字符 
    5 S.isdigit()                          #是否全是数字,并至少有一个字符 
    6 S.isspace()                          #是否全是空白字符,并至少有一个字符 
    7 S.islower()                          #S中的字母是否全是小写 
    8 S.isupper()                          #S中的字母是否便是大写 
    9 S.istitle()                          #S是否是首字母大写的
    >>> a='hello world'
    >>> print(a.startswith('hel'))
    True
    >>> a.endswith('world')
    True

    12.字符串切片

    
    
     1 str = '0123456789′
     2 print str[0:3] #截取第一位到第三位的字符
     3 print str[:] #截取字符串的全部字符
     4 print str[6:] #截取第七个字符到结尾
     5 print str[:-3] #截取从头开始到倒数第三个字符之前
     6 print str[2] #截取第三个字符
     7 print str[-1] #截取倒数第一个字符
     8 print str[::-1] #创造一个与原字符串顺序相反的字符串
     9 print str[-3:-1] #截取倒数第三位与倒数第一位之前的字符
    10 print str[-3:] #截取倒数第三位到结尾
    11 print str[:-5:-3] #逆序截取,截取倒数第五位数与倒数第三位数之间
    
    

     13、分割,前中后三部分

    partition() 方法用来根据指定的分隔符将字符串进行分割。

    如果字符串包含指定的分隔符,则返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。

    partition() 方法是在2.5版中新增的。

    语法

    str.partition(str)

    参数

    str : 指定的分隔符。

    返回值

    返回一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串。

    
    
    >>> a='good boy'
    >>> a.partition(' ')
    ('good', ' ', 'boy')
    >>>
    >>> a.partion('x')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'str' object has no attribute 'partion'
    >>>
    
    

    14、替换

    
    
    1 s="alex SB alex"
    2 s.replace("al","BB")
    3 print(ret)
    4 #输出结果    BBex SB BBex
    
    

    15、按输入字符切割

    
    
    >>> a='goodxmorningxboyxandxgirl'
    >>> a.split('x')
    ['good', 'morning', 'boy', 'and', 'girl']
    >>>
    
    

    16、根据换行执行分割

    >>> s='hello	world
    !'
    ['hello	world', '!']
    >>>

    17、大写变小写,小写变大写

    
    
    >>> s="alExAlec"
    >>> s.swapcase()
    'ALeXaLEC'
    >>>
    
    

    18、变成标题

    
    
    >>> a='hello world'
    >>> a.title()
    'Hello World'
    >>>

    19、Python zfill() 方法返回指定长度的字符串,原字符串右对齐,前面填充0。

    语法:

    str.zfill(width)

    参数

    • width -- 指定字符串的长度。原字符串右对齐,前面填充0。

    返回值

    返回指定长度的字符串。

    
    
    >>> str='good boy'
    >>> str.zfill(40)
    '00000000000000000000000000000000good boy'
    >>>
    
    
    
     
    
    
  • 相关阅读:
    ConcurrentHashMap之实现细节
    Java 开发 2.0: 用 Hadoop MapReduce 进行大数据分析
    mapreduce从wordcount开始
    centos 5.5 安装mysql 5.5 全程详细记录 RPM方式安装
    使用GDAL工具对OrbView3数据进行正射校正
    centos 5.5 mysql5.5 乱码
    netty vs mina netty和mina的区别
    VC欣赏、家人是阻力,极客化、国际化——90后创业生态
    悲惨而又丢人的创业经历:草根创业者含恨倾诉为什么失败
    悲惨而又丢人的创业经历:草根创业者含恨倾诉为什么失败
  • 原文地址:https://www.cnblogs.com/weststar/p/11340422.html
Copyright © 2011-2022 走看看