• Python 字符串常用方法 day2


    1、去空格和换行符:

    s = '  a   bc   '
    print(s.strip())#strip(),去掉字符串两边的空格和换行符,无法去除中间的空格
    print(s.rstrip())#rstrip(),去掉右边的空格
    print(s.lstrip())#lstrip(),去掉左边的空格

    2、替换:

    print(s.replace('a','A')) #把a替换为A,返回一个新的字符串,只替换不会更改原字符串
    print(s.replace('   ',''))#把空格替换为空字符串

    3、找下标:

    s = 'abc'
    print(s.index('c')) #找下标
    print(s.find('a')) #找下标,若元素存在则同index
    print(s.find('e')) #找不存在的下标,返回-1,用find
    # print(s.index('f'))#找不存在的下标,报错ValueError

    4、大小写

    print(s.upper()) #把所有字母都变为大写
    print(s.lower()) #把所有字母都变为小写
    print(s.capitalize())#首字母大写,其余小写
    print(s.title())#标题化,所有单词的首字母大写

    5、补齐

    print(s.center(50,'='))#把原字符串放在中间,若不够50,则将补齐50
    print(s.center(5,'*'))

    6、统计次数

    print(s.count('c')) #找某个字符出现的次数

    7、补零

    s2 = '1'
    print(s2.zfill(5)) #在前面补0,补5-1个0

    8、各种判断 

    print(s.startswith('a'))#true ,判断是否已xx开头
    print(s.endswith('.jpg'))#false,判断是否已xx结尾
    print(s.isdigit())#判断字符串里存的是否为整数
    print(s2.islower())#是不是全是小写字母 ,数字应都是false
    print(s2.isupper())#是不是全是大写字母
    print(s2.isalpha())#是字母或汉字,全都返回true
    print(s2.isalnum())#只有数字或字母或汉字会返回true,其他的全返回false(用于不允许输入特殊字符的情况)
    print(s2.isspace())#判断是否都是空格

    9、字符串格式化

    s3 = '今天是{},欢迎{}登录'
    s4 = 'insert into stu (id,username,passwd,phone) value ("{id}","{username}","{password}","{phone}")'
    
    print(s3.format('2019','小明')) #做字符串格式化的
    print(s4.format(username = 'abc',id = 1,password = 'abc12323',qq = '2345123453',phone = '1324235435'))
    print(s4.format_map({"username":"abc",'id':1,"password":"dfasdf","phone":'245432534'}))#传一个字典

    10、分割字符串(常用)

    stus='xiaoming,xiaohei,xiaobai,jaojun'
    print(stus.split(',')) #分割字符串,常用!!! 以逗号分割
    example = 'a b c d ef 123'
    print(example.split())#什么都不写,则以空格分割
    print(example.split('.'))#没有句号 则将字符串放到一个list里

    11、连接字符串(常用)

    l = ['xiaoming', 'xiaohei', 'xiaobai', 'jaojun']
    
    print(','.join(l)) #把list里面的每一个元素通过指定的字符串连接起来
    print(' '.join(l)) #用空格把元素连接起来




  • 相关阅读:
    页面切换语言包使用session不用cookie
    如何设置unobtrusive的语言包
    .net MVC全球化资源使用心得
    消息队列写入内容后,读出来的自动包裹了<string>标签,自定义格式化器解决该issue
    解决"415 Cannot process the message because the content type 'application/x-www-form-urlencoded' was not the expected type 'text/xml; charset=utf-8'"
    动态sql语句输出参数
    vue数据更改视图不更新问题----深入响应式原理
    实现 页面某些 效果
    自己封装 vue 组件 和 插件
    单页面应用的 打包部署(vue-cli、creat-react-app )
  • 原文地址:https://www.cnblogs.com/candysalty/p/10944927.html
Copyright © 2020-2023  润新知