zoukankan      html  css  js  c++  java
  • python中字符串的常见操作(一)

    如有字符串:

    str1 = '192.168.1.1'
    str2 = 'asdfghjk'
    str3 = 'Asd fg hj ki'
    str4 = ' '
    str5 = ''

    以下是常见操作:
    # isalpha()判断字符串是否是字符

    >>> res = str1.isalpha()
    >>> print(res)
    False

    # isalnum()判断是否是数字或者字符组成

    >>> res = str1.isalnum()
    >>> print(res)
    False

    # isdigit()判断是否是整数

    >>> res = str1.isdigit()
    >>> print(res)
    False

    #rfind()从右往左找第一个对应的值,显示的是正向索引,如果没找到匹配的值返回-1

    >>> res = str1.rfind('.',0,3)
    >>> print(res)
    -1
    >>> res = str1.rfind('.')
    >>> print(res)
    9

    # find()从左往右找第一个对应的值,显示的是正向索引,如果没找到匹配的值返回-1

    >>> res = str1.find('.',0,3)
    >>> print(res)
    -1
    >>> res = str1.find('.')
    >>> print(res)
    3

    # index()从左往右找第一个对应的值,显示的是正向索引,如果没找到匹配的值报错

    >>> res = str1.index('.')
    >>> print(res)
    3
    >>> res = str1.index('.',0,4)
    >>> print(res)
    3
    >>> res = str1.index('.',4,8)
    >>> print(res)
    7
    >>> res = str1.index('12')
    >>> print(res)
    res = str1.index('12')
    ValueError: substring not found 

    # count()显示字符个数,如果没有显示0

    >>> res = str1.count('q')
    >>> print(res)
    0
    >>> res = str1.count('1')
    >>> print(res)
    4
    >>> res = str1.count('1',0,6)
    >>> print(res)
    2
    >>> res = str1.count('16')
    >>> print(res)
    1

    #把字符串变成抬头(每个单词的开头变成大写,数字不会报错)

    >>> res = str1.title()
    >>> print(res)
    192.168.1.1
    >>> res = str2.title()
    >>> print(res)
    Asdfghjk
    >>> res = str3.title()
    >>> print(res)
    Asd Fg Hj Ki

    #判断字符串当中开头字符是否为所选的字符

    >>> res = str1.startswith('1')
    >>> print(res)
    True
    >>> res = str2.startswith('A')
    >>> print(res)
    False
    >>> res = str3.startswith('A')
    >>> print(res)
    True

    #判断字符串当中结尾字符是否为所选的字符

    >>> res = str3.endswith('ki')
    >>> print(res)
    True
    >>> res = str3.endswith('j ki')
    >>> print(res)
    True
    >>> res = str3.endswith('jki')
    >>> print(res)
    False 

    #isspace判断是否是由空格组成

    >>> res = str3.isspace()
    >>> print(res)
    False
    >>> res = str4.isspace()
    >>> print(res)
    True
    >>> res = str5.isspace()
    >>> print(res)
    False 

    pycharm快捷键
      # ctrl + d:复制一行
      # ctrl + ?:快速注释一行|撤销
      # tab键:缩进4个空格
      # shift+tab键:回退4个空格

    作者:无荨

    -------------------------------------------

    个性签名:学IT,就要做到‘活到老学到老’!

    如果觉得这篇文章对你有小小的帮助的话,别忘记点个“推荐”哦!

  • 相关阅读:
    【转】Web Service单元测试工具实例介绍之SoapUI
    【节选】刘积仁:怎样才是真正的创业者
    xadmin引入django-import-export导入功能
    django使用xadmin
    Mac Docker安装Redis4.0
    JMeter+Maven+CSV数据驱动
    Selenium+TestNG+CSV数据驱动
    JMeter压测时报“内存不足”故障的9个简单解决方案
    requests+unittest+ddt+xlrd+pymysql+BeautifulReport数据驱动
    Mac Docker安装MySQL5.7
  • 原文地址:https://www.cnblogs.com/twoo/p/11641738.html
Copyright © 2011-2022 走看看