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

    字符串定义

    s1 = 'string'
    s2 = "string"
    s3 = '''this's a "string"'''
    s4 = 'hello 
     klvchen.com'
    s5 = r"hello 
     klvchen"
    s6 = 'c:windows
    t'
    s7 = R"c:windows
    t"
    s8 = 'c:windows\nt'
    sql = """select * from user where name='tom'""""
    

    字符串的拼接

    a = "hello"
    b = "klvchen"
    c = a + b
    print(c)
    结果:
    helloklvchen
    
    

    注意:该方法效率比较低,推荐使用 join 方法

    a = "hello"
    b = "klvchen"
    c = " ".join([a, b])
    print(c)
    结果:
    hello klvchen
    
    

    字符串的各种方法

    统计元素个数

    str = "hello klvchen"
    print(str.count('l'))             
    结果:
    3
    

    首字母大写

    str = "hello klvchen"
    print(str.capitalize())
    结果:
    Hello klvchen
    

    居中

    str = "hello klvchen"
    print(str.center(50,'#'))
    结果:
    ##################hello klvchen###################
    

    判断是否以某个内容结尾

    str = "hello klvchen"
    print(str.endswith('chen'))
    结果:
    True
    

    判断是否以某个内容开始

    str = "hello klvchen"
    print(str.startswith('tt'))
    结果:
    False
    

    设置 tab 的 size

    str = "hello 	klvchen"
    print(str.expandtabs(tabsize=30))
    结果:
    hello                         klvchen
    

    查找第一个元素,并返回索引

    str = "hello klvchen"
    print(str.find('t'))
    print(str.find('l'))
    结果:
    -1
    2
    

    format

    str = "hello {name}"
    print(str.format(name='klvchen'))
    结果:
    hello klvchen
    

    format_map

    str = "hello {name} is {age}"
    print(str.format_map({'name':'klvchen','age':28}))
    结果:
    hello klvchen is 28
    

    去除字符串两边空格及tab

    str = ' hello world '
    print(str.strip())
    结果:
    hello world
    

    替换字符串

    str = 'hello world'
    print(str.replace('o', 'a'))             # 全部替换
    print(str.replace('o', 'a', 1))         # 只替换一次
    结果:
    hella warld 
    hella world 
    

    切割字符串

    str = 'hello world'
    print(str.split(' '))
    结果:
    ['hello', 'world']
    
  • 相关阅读:
    使用jedis连接redis
    布隆过滤器redis缓存
    SQL与NOSQL
    Charles 移动端抓包工具,使用方法以及注意事项
    安装npm包的时候报错rollbackFailedOptional: verb npm-session
    You may need an appropriate loader to handle this file type.
    数组去重
    判断两个数组是否相等(包括数组里边的键值对是否相等)
    数组里的字符串转为数字
    背景色铺满整个屏幕
  • 原文地址:https://www.cnblogs.com/klvchen/p/8624649.html
Copyright © 2011-2022 走看看