python字符串(一):拼接、查找、分割、替换

    xiaoxiao2022-07-15  134

    1.字符串定义 字符串:以双引号或单引号包围的数据 2.字符串的拼接 练习:

    a = 'hello' b = 'world' c = a + b print(c) 运行结果:helloworld

    3.特殊字符

    \ \反斜杠符号\ ’单引号\ "双引号\a响铃\b退格\000空\n换行\v纵向制表符\t横向制表符\r回车\f换页

    4.字符串格式化

    %s字符串占位符%d数字占位符%f浮点型数字占位符/控制浮点型数字占位符

    练习:

    print('my name is %s'%('ming')) 结果:my name is ming

    5.字符串的查找方法

    count计数功能,返回自定字符在字符串中的个数find查找,返回从左第一个指定字符的索引,找不到返回-1rfind查找,返回从右第一个指定字符的索引,找不到返回-1index查找,返回从左附一个指定字符的索引,找不到报错rindex查找,返回从右第一个指定字符的索引,找不到报错

    练习:count

    test = 'hello world' print(test.count('o')) 运行结果:2

    练习:find

    test = 'hello world' print(test.find('world')) 运行结果:6 test = 'hello world' print(test.find('word')) 运行结果:-1

    练习rfind

    test = 'hello world' print(test.rfind('world')) 运行结果:6 test = 'hello world' print(test.rfind('word')) 运行结果:-1

    练习:index

    test = 'hello world' print(test.index ('o')) 运行结果:4 test = 'hello world' print(test.index ('q')) 运行结果:ValueError: substring not found

    练习rindex

    test = 'hello world' print(test.rindex ('o')) 运行结果:7

    6.字符串的分割

    partition把字符串从指定位置分成三部分,从左开始 的第一个字符rpartition类似partition,从右开始splitlines识别每行的\n并合并且分割输出

    练习:partition

    test = 'hello world' print(test.partition('o')) 运行结果:('hell', 'o', ' world')

    练习:rpartition

    test = 'hello world' print(test.rpartition('o')) 运行结果:('hello w', 'o', 'rld')

    练习:splitlines

    test = 'hello\nworld' print (test) print(test.splitlines()) 运行结果:hello world ['hello', 'world']

    7.字符串的替换

    replace从左到右替换指定元素,可以指定替换个数,默认全部替换

    练习replace

    test = 'hello world' print (test) print(test.replace('o','x')) 运行结果:hello world hellx wxrld
    最新回复(0)