zoukankan      html  css  js  c++  java
  • Python 字符串中常见的一些方法续

    统计某个字符(sub)在字符串(str)中出现的次数

    str.count(sub, start= 0,end=len(string))

    sub -- 搜索的子字符串

    start -- 字符串开始搜索的位置,默认字符索引值0。

    end -- 字符串结束搜索的位置,默认字符串索引值len(str)。

    返回子字符串在字符串中出现的次数。

    str = "this is string examples"
    
    print(str.count("s"))
    print(str[5:])
    print(str.count("s",5,len(str)))

    结果:

    4
    is string examples
    3

    str.split(str1="", num=str.count(str1))

    通过指定的分隔符(str1="")对字符串(str)进行切片,num为分割的次数,默认分隔所有(num=str.count(str1)。

    str1 -- 分隔符,默认所有空字符,包括空格,换行( ),制表符( )。

    num -- 分割次数。默认分割所有。

    返回分割后字符串的列表。

    str = "this is string example!"

    print(str.count(" ")) print(str.split(" ",3)) print(str.split(" "))

    结果:

    3
    ['this', 'is', 'string', 'example!']
    ['this', 'is', 'string', 'example!']

    指定分隔符和分割次数:

    str = "this is string example!"
    
    print(str.split("i"))
    print(str.split("i",2))

    结果:

    ['th', 's ', 's str', 'ng example!']
    ['th', 's ', 's string example!']


    str.splitlines([keepends])

    按照行(' ',' ',' ')分隔,返回一个把各行作为元素的列表。

    keepends -- 在输出结果里是否去掉换行符(' ',' ',' ')。

    默认 Fals --不保留换行符。True -- 保留换行符。

    返回一个包含各行作为元素的列表。

    str = '''this 
    is 
    string 
    example!
    '''
    print(str.splitlines())

    结果:

    ['this ', 'is ', 'string ', 'example!']

    str.join(sequence)

    可以用指定字符(str)连接序列中的元素生成一个字符串。

    sequence -- 需要连接的元素序列。注意:序列中的元素必须是字符串。

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

    list = ["apple","lemon","banana"]
    
    print("-".join(list))

    结果:

    apple-lemon-banana

    str.replace(old, new[, max])

    可以把字符串中的 old(就字符串)替换成 new(新字符串),默认全部替换。

    若指定 max,替换前 max个。

    old -- 将要被替换掉的字符串。

    new -- 新字符串,顶替 old的字符串。

    max -- 可选。替换前 max个。

    返回字符串中 old 被 new 替换后生成的新字符串。

    str = "apple,lemon,banana,apple,apple,apple"
    
    print(str.replace("apple","orange",3))

    结果:

    orange,lemon,banana,orange,orange,apple

     

     

  • 相关阅读:
    第一次被队友说给力
    An Unfair Game-[ACdream1035]
    男人八题解题报告
    it's hard to say
    剪花布条[HDU2087]
    1117: 无序字母对 character
    20181101
    20181104
    20181102
    20181031
  • 原文地址:https://www.cnblogs.com/orangeJJJ/p/10145124.html
Copyright © 2011-2022 走看看