zoukankan      html  css  js  c++  java
  • 字符串操作

    一、字符串基础

    1、字符串定义

    使用成对的单引号、双引号或者三引号将其进行包裹。

    name='hello'
    
    name="hello"
    
    #保留字符串格式信息
    name='''hello  
            word
         '''

    2、字符串与转义字符

    如果字符串中间有正常的字符,不进行区别就会报错,python解释器无法判断单引号是正常字符还是多余单引号,例如:

    s1='It's pencil'
    print(s1)
    
    
    File "<ipython-input-6-efe6d2ca4c27>", line 1
        s1='It's pencil'
               ^
    SyntaxError: invalid syntax

    解决方法:

      使用双引号将单引号扩起来

    s1="It's pencil"
    print(s1)
    
    It's pencil

    如果内部是双引号,可以使用单引号扩起来

    但是如果同时输出单引号和双引号,那又怎么办呢?,这时就需要使用转义字符。

    s1="It's pencil,and not "pen""
    print(s1)
    
    It's pencil,and not "pen"

    这样就可以解决同时输出单引号和双引号了,其实这也是可以解决只输出单引号或者双引号的问题。

    3、转义字符的其它用法

    转义字符不但可以输出单、双引号,并且还能控制字符串的输出格式。

    (1)换行符

    s3="ni
    hao"
    print(s3)
    
    ni
    hao

    (2)混合输出

    如果输出的既有数字又有字符串,该如何处理呢?可以现将数字转为字符串,然后再进行处理

    s4=str(56)+"nihao" + "
    " +str(89)
    print(s4)
    
    56nihao
    89

    (3)原始字符串输出

    当然如果不希望转义特殊字符,输出原始字符,就用到了repr()函数

    s5="ni
    hao"
    print(repr(s5))
    
    'ni
    hao'

    也可以在字符串前面加上r

    s5=r"ni
    hao"
    print(s5)
    
    ni
    hao

    所以如果让一个字符串不进行转义,输出原始格式有以下三种方式:

    • 转义符()
    • repr()函数
    • 字符串前面加r

    3、拼接字符串

    字符串有时会很长,需要用到字符串的拼接,先看两个字符串的拼接。

    s2="ni"  "hao"
    print(s2)
    
    nihao

    这种写法是可以将字符串进行拼接,并且中间可以有n个空格,但是不能有换行符。

    s2="ni"
    s3="hao"
    print(s2 s3)
    File
    "<ipython-input-11-624f32903065>", line 3 print(s2 s3) ^ SyntaxError: invalid syntax

    但是对于字符串变量是不可以的,Python解释器会报语法错误,这时需要使用“+”进行拼接

    s2="ni"
    s3="hao"
    print(s2+s3)
    
    nihao

    4、长字符串

    在字符串中提到了三引号包裹字符串,三引号进行输出会成为一个长字符串,它保留原始格式。

    单、双引号混用,不需要加转义符

    s6="""
    It's my pencil,not "pen"
    """
    print(s6)
    
    It's my pencil,not "pen"

    长字符串只需在每一行结尾处输入"",这样的话转行就被转义了,变成一行字符串

    s7="""ni
    hao"""
    print(s7)
    
    nihao

    二、字符串基本操作

    1、索引

    根据字符串索引取值,索引为0取出字符串第一个值,索引为-1取出倒数第一个,索引从0(前向)或-1(后向)开始。

    s8="hello word"
    print(s8[0]) #h
    print(s8[-1]) #d

    Forward index

    0

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    string

    h

    e

    l

    l

    o

    w

    o

    r

    l

    d

    Backward index

    -11

    -10

    -9

    -8

    -7

    -6

    -5

    -4

    -3

    -2

    -1


    2、切片

    语法:[start : finish]

    •  start:子序列开始位置的索引值
    •  finish:子序列结束位置的下一个字符的索引值

    如果不提供 start 或者 finish,默认 start 为第一 个字符开始,finish 为最后一个字符

    s8="hello word"
    print(s8[1:4]) #ell
    print(s8[:5]) #hello
    print(s8[-3:]) #ord

    另外切片接受三个参数的情况:

    [start : finish : countBy]

    •  默认 countBy 为 1
    s8="hello word"
    print(s8[::2])#hlowr 每隔一个取一个字符

    获取逆串

    s8="hello word"
    print(s8[::-1]) #drow olleh

    3、乘法

    字符串中使用乘法

    s9='mnk'
    print(10*s9)#mnkmnkmnkmnkmnkmnkmnkmnkmnkmnk
    print(s9*10)#mnkmnkmnkmnkmnkmnkmnkmnkmnkmnk

    4、判断是否包含值

    使用用in判断字符串中是否包含其中的一部分,如果是,返回True,否则返回False

    s10="hello word"
    print('h' in s10)#True
    print('o' not in s2)#True

    5、获取字符串的长度

    使用了len()方法获取字符串长度

    s11="hello word"
    print(len(s11)) #10

    6、获取最小值

    按照ASCII获取最小字符

    s11="helloword"
    print(min(s11)) #d

    7、获取最大值

    按照ASCII获取最大字符

    s11="helloword"
    print(max(s11))#w

    三、字符串格式化

    如果一个字符串中有一部分是固定的,而另一部份是动态变化的,那么可以将固定部分做成模板,动态变化的部分用“%”进行替换。“%”后面根据不同数据类型进行格式化参数。

    例如:

    • %d 整数
    • %f 浮点型
    • %f 字符串

    等参数。如果要在格式化字符串中显示百分号就需要使用两个百分号(%%),否则就会因为数量不匹配抛出异常。

    1、模板字符串

    在string模块中有一个用于格式化的Template类的构造方法,该类功能是用同一个值替换所有的相同的格式化参数。参数使用“$”符号开头,格式化时需要使用Template类的substitute()方法。

    from string import Template
    template=Template("$s $s")
    result=template.substitute(s="nihao")
    print(result) #nihao nihao

    当格式化参数是字符串的一部分需要大括号将其区分开

    from string import Template
    template=Template("${s}stitute")
    result=template.substitute(s="sub")
    print(result) #substitute

    2、format()方法

    字符串本身有一个format方法用于格式化字符串,这个与之前的"%"不太一样,它使用的是{},支持按顺序以及关键字格式化字符串。

    • 顺序格式化
    s12="{},{}"
    print(s12.format("hello","world")) #hello,world
    • 关键字格式化
    s12="{a},{b}"
    print(s12.format(a="hello",b="world")) #hello,world
    • 混合格式化

    format传递参数需要前面是按照顺序传递的参数,后面是关键字传递参数。

    s12="{a},{},{b},{}"
    print(s12.format("你好","世界",a="hello",b="world")) #hello,你好,world,世界

    四、字符串主要方法

    1、center()

    用于将一个字符串在一定宽度区域居中显示,并且在字符串两侧填入制定字符长度为1的字符串,默认情况填充空格。

        def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
            """
            S.center(width[, fillchar]) -> str
            
            Return S centered in a string of length width. Padding is
            done using the specified fill character (default is a space)
            """
            return ""
    center()方法
    s13="hell0"
    print(s13.center(30))#hello
    print(s13.center(30,"*"))#************hell0*************

    2、find()

    用于在一个大字符串中查找小字符串,如果找到,find()方法返回子字符串在大字符串中出现的第一个位置,如果没找到,返回-1。

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

    find()方法可以指定查找开始和结束的位置。使用第二个和第三个参数。

    s14="Hello World"
    print(s14.find("ll",2,7))#2

     3、join()

    用于连接序列中的元素。

        def join(self, *args, **kwargs): # real signature unknown
            """
            Concatenate any number of bytes/bytearray objects.
            
            The bytearray whose method is called is inserted in between each pair.
            
            The result is returned as a new bytearray object.
            """
            pass
    join()方法
    list=['A','B','C','D']
    s15='*'
    print(s15.join(list)) #A*B*C*D  将字符串s15与列表中的每个元素进行相连,然后将连接的结果进行合并

    注意:与字符串连接的序列元素必须是字符串类型,如果是其它类型就会报错。

    4、split()

    split()方法与join()方法互为逆方法,split()方法将一个字符串通过分隔符拆成一个序列,如果split()方法不指定任何参数,就会把所有空格作为分隔符。

       def split(self, *args, **kwargs): # real signature unknown
            """
            Return a list of the sections in the bytearray, using sep as the delimiter.
            
              sep
                The delimiter according which to split the bytearray.
                None (the default value) means split on ASCII whitespace characters
                (space, tab, return, newline, formfeed, vertical tab).
              maxsplit
                Maximum number of splits to do.
                -1 (the default value) means no limit.
            """
            pass
    split()方法
    s17="h e l l 0"
    print(s17.split())#['h', 'e', 'l', 'l', '0']
    s16="A*B*C*D"
    print(s16.split('*'))#['A', 'B', 'C', 'D']

    5、lower()、upper()和capwords()方法

    lower()、upper()方法分别是将字符串中所有字母字符转换为小写和大写,capwords()是将字符串中每个单独的单词的首字母转换为大写。

        def lower(self): # real signature unknown; restored from __doc__
            """
            B.lower() -> copy of B
            
            Return a copy of B with all ASCII characters converted to lowercase.
            """
            pass
    lower()方法
        def upper(self): # real signature unknown; restored from __doc__
            """
            B.upper() -> copy of B
            
            Return a copy of B with all ASCII characters converted to uppercase.
            """
            pass
    upper()方法
    def capwords(s, sep=None):
        """capwords(s [,sep]) -> string
    
        Split the argument into words using split, capitalize each
        word using capitalize, and join the capitalized words using
        join.  If the optional second argument sep is absent or None,
        runs of whitespace characters are replaced by a single space
        and leading and trailing whitespace are removed, otherwise
        sep is used to split and join the words.
    
        """
        return (sep or ' ').join(x.capitalize() for x in s.split(sep))
    capwords()方法
    s18="HELLO"
    s19="word"
    print(s18.lower())#hello
    print(s19.upper())#WORD
    import string
    s20="it is pencil"
    print(string.capwords(s20))#It Is Pencil

    6、replace()

    用于将一个字符串中的子字符串替换为另外一个字符串,该方法返回替换后的子字符串,如果在原字符串中未找到要替换的子串,那么该方法返回原字符串,replace()方法就是一个查找替换的过程。

        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
    replace()方法
    s21="hello world"
    print(s21.replace('world','bright')) #hello bright

    7、strip()

    用于截取字符串的前后空格或者指定的字符。

        def strip(self, *args, **kwargs): # real signature unknown
            """
            Strip leading and trailing bytes contained in the argument.
            
            If the argument is omitted or None, strip leading and trailing ASCII whitespace.
            """
            pass
    strip()方法
    • 用于截取前后空格
    s22="  hello world  "
    print(s22.strip())#hello world
    • 用于截取指定字符
    s23="hello world"
    print(s23.strip("hd"))#ello worl

    注意:

    • strip()方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

    8、translate()、maketrans()

      translate方法与replace()方法类似,都是用来替换字符串中的一部分,只不过translate()方法用来替换单个字符,而replace()方法用来替换一个子字符串,所以translate()方法的效率比replace()方法也更高一些。

      在使用translate()方法之前需要使用maketrans()方法创建一个替换表。

    s24="I like apple and pear"
    #创建替换表,将a,e分别替换为m,k
    table=s24.maketrans('ae','mk')
    print(table)#{97: 109, 101: 107}
    print(s24.translate(table))#I likk mpplk mnd pkmr

      当然替换表可以指定第三个参数,表示要删除的字符

    s24="I like apple and pear"
    #创建替换表,将a,e分别替换为m,k,并且删除空格
    table=s24.maketrans('ae','mk'," ")
    print(table){32: None, 97: 109, 101: 107}
    print(s24.translate(table))#Ilikkmpplkmndpkmr

    注意:

    • translate()方法替换的不止一个字符,如果有多个字符满足条件,那么就替换所有的满足条件的字符
    • maketrans()方法第三个参数指定了要删除的字符,只能删掉长度为1的字符,而不是字符串。

    五、字符串其它方法

    1、zfill()

    返回指定长度的字符串,原字符串右对齐,前面填充0。

        def zfill(self, width): # real signature unknown; restored from __doc__
            """
            B.zfill(width) -> copy of B
            
            Pad a numeric string B with zeros on the left, to fill a field
            of the specified width.  B is never truncated.
            """
            pass
    zfill()方法
    person = "my name is bright}, i am 27 years old"
    print(person.zfill(50)) #0000000000000my name is bright}, i am 27 years old 指定字符串长度,不足就是用0来填充

    2、lstrip()

    用于截掉字符串左边的空格或指定字符。

        def lstrip(self, chars=None): # real signature unknown; restored from __doc__
            """
            S.lstrip([chars]) -> str
            
            Return a copy of the string S with leading whitespace removed.
            If chars is given and not None, remove characters in chars instead.
            """
            return ""
    lstrip()方法
    person = "my name is bright, i am 27 years old"
    print(person.lstrip("my name")) #is bright, i am 27 years old

    3、swapcase()

    大小写互换

        def swapcase(self): # real signature unknown; restored from __doc__
            """
            S.swapcase() -> str
            
            Return a copy of S with uppercase characters converted to lowercase
            and vice versa.
            """
            return ""
    swapcase()方法
    person = "my name is bright, i am 27 years old"
    print(person.swapcase()) #MY NAME IS BRIGHT, I AM 27 YEARS OLD

    4、ljust()和rjust()

    ljust()方法返回一个原字符串左对齐,并使用空格填充至指定长度的新字符串,如果指定的长度小于原字符串的长度则返回原字符串;rjust则相反。

        def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__
            """
            B.ljust(width[, fillchar]) -> copy of B
            
            Return B left justified in a string of length width. Padding is
            done using the specified fill character (default is a space).
            """
            pass
    ljust()方法
    person = "my name is bright, i am 27 years old"
    print(person.ljust(50,"-"))#my name is bright, i am 27 years old--------------
    person = "my name is bright, i am 27 years old"
    print(person.rjust(50,"-"))#--------------my name is bright, i am 27 years old

    5、isalnum、isdecimal、isalpha、isidentifier、islower、isupper、isnumeric、isprintable、isspace以及istitle

    这些方法分别是判断是否是a-z A-Z 0-9,一个正整数、合法的关键字、小写、大写、只由数字组成、打印、空格、英文标题

    print("ala".isalnum()) #a-z A-Z 0-9 True
    print("192938".isdecimal())#是不是一个正整数 True
    print("Aa".isalpha())#是不是字母 True
    print("-a".isidentifier())#是不是合法的关键字,是不是合法的变量名 False
    print("A".islower()) #False
    print("A".isupper())#True
    print("123.3".isnumeric())#是否都是由数字组成 False
    print("a".isprintable())#可否打印 True
    print("".isspace())#是不是空格 False
    print("Today Headline".istitle())#是不是英文标题 True

    6、capitalize()

    首字母大写

        def capitalize(self): # real signature unknown; restored from __doc__
            """
            B.capitalize() -> copy of B
            
            Return a copy of B with only its first character capitalized (ASCII)
            and the rest lower-cased.
            """
            pass
    capitalize()方法
    person = "my name is bright, i am 27 years old"
    print(person.capitalize()) #首字母大写 My name is bright, i am 27 years old

    7、casefold()

    大写变小写

        def casefold(self): # real signature unknown; restored from __doc__
            """
            S.casefold() -> str
            
            Return a version of S suitable for caseless comparisons.
            """
            return ""
    casefold()方法
    person = "my Name is bright, i am 27 years old"
    print(person.casefold()) #大写变小写 my name is bright, i am 27 years old

    8、count()

    用于统计字符串里某个字符出现的次数。可选参数为在字符串搜索的开始与结束位置

        def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.count(sub[, start[, end]]) -> int
            
            Return the number of non-overlapping occurrences of substring sub in
            string S[start:end].  Optional arguments start and end are
            interpreted as in slice notation.
            """
            return 0
    count()方法
    person = "my name is bright, i am 27 years old"
    print(person.count('m',3,30)) #2 从索引3开始到索引30结束

    9、endswith()

    用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。

        def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.endswith(suffix[, start[, end]]) -> bool
            
            Return True if S ends with the specified suffix, False otherwise.
            With optional start, test S beginning at that position.
            With optional end, stop comparing S at that position.
            suffix can also be a tuple of strings to try.
            """
            return False
    endswith()方法
    person = "my name is bright, i am 27 years old"
    print(person.endswith('old',3,40)) #True

    10、index()方法

    检测字符串中是否包含子字符串 str,如果包含子字符串返回开始的索引值,否则抛出异常,可以指定开始和结束的索引值。

        def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
            """
            S.index(sub[, start[, end]]) -> int
            
            Like S.find() but raise ValueError when the substring is not found.
            """
            return 0
    index()方法
    person = "my name is bright, i am 27 years old"
    print(person.index('old',3,40)) #33

    字符串是不可变对象,调用自身的任意方法,也不会改变其自身的内容。相反,这些方法会创建新的对象并返回,这样,就保证了不可变对象本身永远是不可变的。

  • 相关阅读:
    第1章 初涉MySQL
    成绩转换
    【JSTL】--附加:c:import,c:url;c:param,c:redirect--drp217
    【JSTL】--JSTL表达式:c:forEach,varstatus/begin end/循环控制标签--drp215
    【JSTL】--JSTL表达式:c:forEach--drp215
    【JSTL】--JSTL表达式:c:set,c:if,c:choose,--drp214
    【JSTL】--c:out演示--drp213
    【JSTL】--测试EL表达式--drp212~
    【JSTL】--读取实体成员变量吗?--drp212
    【JSTL】--测试EL表达式--drp212
  • 原文地址:https://www.cnblogs.com/shenjianping/p/10988012.html
Copyright © 2011-2022 走看看