zoukankan      html  css  js  c++  java
  • python 字符串 大小写转换 以及一系列字符串操作技巧

     

    总结

    capitalize() 首字母大写,其余全部小写
      upper() 全转换成大写
      lower() 全转换成小写
      title() 标题首字大写,如"i love python".title() "I Love Python"

     

    转换大小写

    和其他语言一样,Python为string对象提供了转换大小写的方法:upper() 和 lower()。还不止这些,Python还为我们提供了首字母大写,其余小写的capitalize()方法,以及所有单词首字母大写,其余小写的title()方法。函数较简单,看下面的例子:

    python 字符串 大小写转换 - 波博 - A Pebble Caves = 'hEllo pYthon'

    python 字符串 大小写转换 - 波博 - A Pebble Caveprint s.upper()

    python 字符串 大小写转换 - 波博 - A Pebble Caveprint s.lower()

    python 字符串 大小写转换 - 波博 - A Pebble Caveprint s.capitalize()

    python 字符串 大小写转换 - 波博 - A Pebble Caveprint s.title()

    输出结果:

    HELLO PYTHON

    hello python

    Hello python

    Hello Python

    判断大小写

    Python提供了isupper(),islower(),istitle()方法用来判断字符串的大小写。注意的是:

    1. 没有提供 iscapitalize()方法,下面我们会自己实现,至于为什么Python没有为我们实现,就不得而知了。

    2. 如果对空字符串使用isupper(),islower(),istitle(),返回的结果都为False。

    python 字符串 大小写转换 - 波博 - A Pebble Caveprint 'A'.isupper() #True

    python 字符串 大小写转换 - 波博 - A Pebble Caveprint 'A'.islower() #False

    python 字符串 大小写转换 - 波博 - A Pebble Caveprint 'Python Is So Good'.istitle() #True

    python 字符串 大小写转换 - 波博 - A Pebble Cave#print 'Dont do that!'.iscapitalize() #错误,不存在iscapitalize()方法

    实现iscapitalize

    1. 如果我们只是简单比较原字符串与进行了capitallize()转换的字符串的话,如果我们传入的原字符串为空字符串的话,返回结果会为True,这不符合我们上面提到的第2点。

    python 字符串 大小写转换 - 波博 - A Pebble Cavedef iscapitalized(s):

    python 字符串 大小写转换 - 波博 - A Pebble Cave    return s == s.capitalize( )

    有人想到返回时加入条件,判断len(s)>0,其实这样是有问题的,因为当我们调用iscapitalize('123')时,返回的是True,不是我们预期的结果。

    2. 因此,我们回忆起了之前的translate方法,去判断字符串是否包含任何英文字母。实现如下:

    python 字符串 大小写转换 - 波博 - A Pebble Caveimport string

    python 字符串 大小写转换 - 波博 - A Pebble Cavenotrans = string.maketrans('', '')

    python 字符串 大小写转换 - 波博 - A Pebble Cavedef containsAny(str, strset):

    python 字符串 大小写转换 - 波博 - A Pebble Cave    return len(strset) != len(strset.translate(notrans, str))

    python 字符串 大小写转换 - 波博 - A Pebble Cavedef iscapitalized(s):

    python 字符串 大小写转换 - 波博 - A Pebble Cave    return s == s.capitalize( ) and containsAny(s, string.letters)

    python 字符串 大小写转换 - 波博 - A Pebble Cave    #return s == s.capitalize( ) and len(s) > 0 #如果s为数字组成的字符串,这个方法将行不通

    调用一下试试:

    python 字符串 大小写转换 - 波博 - A Pebble Caveprint iscapitalized('123')

    python 字符串 大小写转换 - 波博 - A Pebble Caveprint iscapitalized('')

    python 字符串 大小写转换 - 波博 - A Pebble Caveprint iscapitalized('Evergreen is zcr1985')

    输出结果:

    False

    False

    True

     

    取出字符串中包含的数字

     

     

     

     

     

  • 相关阅读:
    8-2蒙版初识
    8-1使用自由变换(有些操作和教程不同)
    7-11使用色彩调整图层
    7-10使用历史记录画笔
    7-9将灰度转为彩色
    7-8其他色彩调整
    7-7自动色阶/自动对比度/自动颜色
    7-6替换颜色和色彩范围选取
    7-5匹配颜色
    7-4暗调/高光
  • 原文地址:https://www.cnblogs.com/zhaoyingjie/p/6066254.html
Copyright © 2011-2022 走看看