zoukankan      html  css  js  c++  java
  • 3-5 字符串常用方法

    1、字符串空格和换行符的处理

    1 s = '.abc.abc.BCD,abc.'
    2 # 默认去掉字符串两边的空格和换行符
    3 new_s = s.strip('.')  
    4 print(new_s)  # abc.abc.BCD,abc
    5 # 默认去掉字符串右边的空格
    6 print(s.rstrip('.'))  # .abc.abc.BCD,abc
    7 # 默认去掉字符串左边的空格和换行符
    8 print(s.lstrip('.'))  # abc.abc.BCD,abc.

    2、字符串的统计、替换和大小写转换

     1 s = '.abc.abc.BCD,abc.'
     2 # 某个字符串出现的次数
     3 print(s.count('.')) # 4 
     4 # 找某个字符串下标,如果查找的字符串不存的话,报错
     5 print(s.index('a'))  # 1
     6 # 找某个字符串下标,查找的字符串不存在会返回-1
     7 print(s.find('a'))  # 1
     8 # 把字符串中所有的'abc'替换成'ABC'
     9 print(s.replace('abc','ABC'))  # .ABC.ABC.BCD,ABC.
    10 # 字符串中所有小写字母变成大写字母
    11 print(s.upper())  # .ABC.ABC.BCD,ABC.
    12 # 字符串中所有大写变成小写字母
    13 print(s.lower())  # .abc.abc.bcd,abc.

    3、判断字符串

     1 s = 'python'
     2 
     3 # 首字母大写
     4 print(s.capitalize())  # Python
     5 
     6 # 判断是否以某个字符串开头
     7 print(s.startswith('p'))  # True
     8 
     9 # 判断是否以某个字符串结尾
    10 print(s.endswith('.jpg'))  # False
    11 
    12 # 判断是否都是小写字母
    13 print(s.islower())  # True
    14 
    15 # 判断是否都是大写字母
    16 print(s.isupper())  # False
    17 
    18 # 判断是否为纯数字
    19 print(s.isdigit())  # False
    20 
    21 # 在字符串的两边用某个字符补齐
    22 print(s.center(10,'='))  # ==python==
    23 
    24 # 判断是不是为字母、或者汉字,不能有数字和特殊符号
    25 print(s.isalpha())  # True
    26 
    27 # 字符串里面只要没有特殊字符,就返回true
    28 print(s.isalnum())  # True
    29 
    30 # 是不是一个合法的变量名
    31 print(s.isidentifier())  # True
    32 
    33 s = '  '
    34 s1 = 'aa  bb'
    35 # 检测字符串是否只由空格组成
    36 print(s.isspace())  # True
    37 print(s1.isspace())  # False

    4、字符串补0

    1 s='1'
    2 # 补0
    3 print(s.zfill(3))  # 001
    4 
    5 l = [1,10]
    6 # 在每个元素之前补0
    7 for i in l:
    8     res = '0' + str(i)
    9     print(res, end="  ")  # 01  010

    5、

  • 相关阅读:
    SQL server 导出平面文件时出错: The code page on Destination
    中文字符集编码Unicode ,gb2312 , cp936 ,GBK,GB18030
    C# DataTable 转 List(大家进来讨论讨论)
    CSS3圆角气泡框,评论对话框
    WinForm 换行问题 textbox (转)
    Nhibernate 多对多级联删除
    JS、C# 去除html标签
    Nhibernate 多对多级联更新
    Ext.Ajax.request()方法和FormPanel.getForm().submit()方法,都返回success()方法的差异
    ExtJs 4.2.1 报错:Uncaught TypeError: Cannot call method 'getItems' of null
  • 原文地址:https://www.cnblogs.com/hushaoyan/p/10011435.html
Copyright © 2011-2022 走看看