python字符串

    技术2022-07-11  144

    1、声明方式

    用单引号、双引号、三引号成对表示 至于单引号和双引号在字符串中的语法,和js一样 三引号可以实现换行符 例如:

    a= '''hello world hello JOJO''' print(a);

    执行

    hello world hello JOJO

    2、字符串获取

    1、通过下标获取 是通过数组下标的方式,数组下标不当会造成数组越界 2、通过切片获取 这不是通过数组下标的方式,所以不会数组越界 切片操作一定是从左到右 代码:

    #-*- coding:UTF-8 -*- a="0123456789" print(a[0]) # 切片start end and step都可以省略 # print(a[start:end:step]) # 获取[start,end)区间的字符 # step 的作用,字面意思就是步长,每隔几个元素取一个 print(a[0:2]) print(a[:]) print(a[0:20]) print(a[::2])

    执行

    0 01 0123456789 0123456789 02468

    3、逆向索引 从最后一个元素开始到第一个元素 次序为-1,-2,-3,…,

    print(a[-2:-1]) 8

    3、字符串修改

    1、没法通过下标进行修改 2、只能重新定义一个了

    a="0123456789" a="hello word" print(a) hello word

    4、字符串删除

    1、通过del操作符删除 2、删除的是指针的指向

    #-*- coding:UTF-8 -*- a="0123456789" b="0123456789" print(id(a)) print(id(b)) del a print(a) 39688800 39688800 Traceback (most recent call last): File "d:\CodeProject\vs_python\python\test3.py", line 7, in <module> print(a) NameError: name 'a' is not defined

    5、字符串合并

    1、通过加号合并 2、合并操作可一定程度上修改字符串

    #-*- coding:UTF-8 -*- a="0123456789" b="0123456789" a = a+b print(id(a)) print(id(b)) print(a) 40673984 40606304 01234567890123456789

    6、其他常用操作 1、获取字符串长度

    len(str)

    2、r或R原始字符串控制符号(原样输出不转义)

    print(r"\n\n\n\n\n") \n\n\n\n\n

    3、重复输出字符串*

    print(cat*2) catcat

    4、格式字符串%

    age = 10 print("age = %d" % (age)) age = 10
    Processed: 0.010, SQL: 9