zoukankan      html  css  js  c++  java
  • 铁乐学Python_day03-字符串常用操作方法

    文:铁乐与猫
    2018-3-20

    1)字符串首个字母大写,其它字母也会转换成小写:

    S.capitalize() -> str
    记忆方法:capital(大写字母)

    def capitalize(self): # real signature unknown; restored from __doc__
        """
        S.capitalize() -> str
        
        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.
        """
        return ""
    

    示例:

    s = 'tieleyumao'
    #首字母大写,其它字母变小写(不管有没有非字母隔开)
    s1 = s.capitalize()
    print(s1)
    s18 = 'yun tie Yumo'
    s19 = s18.capitalize()
    print(s19)
    
    返回的结果是:
    Tielemao
    Yun tie yumo
    

    2)全部转换成大写字母 and 全部转换成小写字母:

    注:这一对建议放一起记忆。另这个经常用在验证码功能上。
    输入验证码不区分大小写可靠它去实现。

    S.upper() -> str
    记忆方法:up,向上,可以理解为小写的向上升级都变大写了。

    def upper(self): # real signature unknown; restored from __doc__
        """
        S.upper() -> str
        
        Return a copy of S converted to uppercase.
        """
        return ""
    

    示例:

    s = 'tieleyumao'
    #全部转换成大写字母
    s2 = s.upper()
    print(s2)
    
    返回的结果是:TIELEYUMAO
    

    S.lower() -> str
    记忆方法:lower,减弱,大写减弱就会变成小写了。

    def lower(self): # real signature unknown; restored from __doc__
        """
        S.lower() -> str
        
        Return a copy of the string S converted to lowercase.
        """
        return ""
    

    示例:

    s2 = 'TIELEYUMAO'
    #全部转换成小写字母
    s3 = s2.lower()
    print(s3)
    
    返回的结果是:tieleyumao
    

    3)对字符串操作居中(center):

    S.center(width[, fillchar]) -> str
    记忆方法:center,中心。

    注:需要填参数width宽度的数值进去,如果填的宽度小于字符串宽度,并不会引起改变。
    另外fillchar表示可用你填的字符填充两边空白处。

    def center(self, width, fillchar=None): # real signature unknown; restored from __doc__
        """
        S.center(width[, fillchar]) -> str
        
        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""
    

    示例:

    s = 'tieleyumao'
    #宽度32,字符串居中
    s4 = s.center(32)
    print(s4)
    #宽度32,字符串居中后,两边的空白以*填充
    s5 = s.center(32, '*')
    print(s5)
    
    效果:
               tieleyumao           
    ***********tieleyumao***********
    

    4)对字符串进行大小写翻转:

    S.swapcase() -> str
    记忆方法:swap 交换,case 包围。
    交换包围,像围棋中的黑白子情况突然反过来黑包白,白包黑,大小写翻转。

    def swapcase(self): # real signature unknown; restored from __doc__
        """
        S.swapcase() -> str
        
        Return a copy of S with uppercase characters converted to lowercase
        and vice versa.
        """
        return ""
    

    示例:

    s6 = 'TieLeYuMao'
    #对s6字符串进行大小写反转
    s7 = s6.swapcase()
    print(s6, s7)
    
    效果:
    TieLeYuMao tIElEyUmAO
    

    5)以非字母隔开的每个单词的首字母转换成大写:

    S.title() -> str
    记忆方法:title,标题,头衔,冠军。可以想像成加冕成大写。
    不过在不适宜用的情景下要慎用。

    def title(self): # real signature unknown; restored from __doc__
        """
        S.title() -> str
        
        Return a titlecased version of S, i.e. words start with title case
        characters, all remaining cased characters have lower case.
        """
        return ""
    

    示例:

    s8 = 'tiele mao*yu3catdog'
    s9 = s8.title()
    #title对每个非字母隔开的英文视为一个单词进行操作
    print(s9)
    
    效果:
    Tiele Mao*Yu3Catdog
    

    6)判断以什么为(前缀)开头,以什么为(后缀)结尾,返回布尔值;

    (成组方便记忆,作为判断条件,返回的是布尔值。
    另外可以切片指定判断在第几位以什么为开头之类。)

    S.startswith(prefix[, start[, end]]) -> bool
    S.endswith(suffix[, start[, end]]) -> bool
    记忆方法:start,开头;end 结尾;swith 快速地;

    判断字符串是否以指定前缀开头/后缀结尾,
    如果以指定前缀开头/后缀结尾返回True,否则返回False。
    可选参数"start"与"end"为检索字符串的开始与结束位置。

    def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.startswith(prefix[, start[, end]]) -> bool
        
        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False
    
     def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.endswith(suffix[, start[, end]]) -> bool
        
        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False
    

    #看到方法的说明参数中含start=None,end=None的表示支持对字符串进行加参数切片处理。

    示例:

    s10 = 'tieleYumaoCatDog'
    s11 = s10.startswith('ti')
    print(s11)
    s12 = s10.startswith('Yu')
    print(s12)
    #切片判断从左起数第5位开头是Y前缀为真还是假
    s13 = s10.startswith('Y', 5)
    print(s13)
    s14 = s10.endswith('Dog')
    print(s14)
    #判断从第五位开始至第十位结束,后缀结尾是mao是否为真
    s15 = s10.endswith('mao', 5, 10)
    print(s15)
    返回的结果:s11 = True , s12 = False ,s13 = True s14 = True s15 = True。
    

    7)去除首尾的空格,换行符,tab(制表符,一般为四个空格);

    S.strip([chars]) -> str
    chars -- 移除字符串头尾指定的字符。迭代,可无序排列。

    记忆方法:strip,剥除衣服……;空,国王的新衣。
    除此外,还有lstrip和rstrip的方法,
    分别对应剥除左(left)和右(right)开始计数的字符
    (填入指定要剥除的参数,可无序)

    def strip(self, chars=None): # real signature unknown; restored from __doc__
        """
        S.strip([chars]) -> str
        
        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""
    

    示例1:

    s16 = '  tab    '
    #去除s16首尾的空格,换行符,tab制表符等
    s17 = s16.strip()
    print(s16)
    print(s17)
    
    效果:
      tab  
    tab
    

    示例2:

    name = 'aleX leNb'
    n2 = name.lstrip('al')
    print(n2)
    n3 = name.rstrip('Nb')
    print(n3)
    n4 = name.strip('ab')
    print(n4)
    
    效果为:
    eX leNb
    aleX le
    leX leN
    

    8)通过元素查找索引(下标);

    find和index一起记忆

    S.find(sub[, start[, end]]) -> int (返回索引值,找不到的返回-1)
    S.index(sub[, start[, end]]) -> int (返回索引值,找不到的报异常)
    记忆方法:find,查找;index,索引。
    要注意的是一次只能返回最先找到的字符索引,和office中的查找有点相似。

    find() 方法检测字符串中是否包含子(sub)字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果包含子字符串返回开始的索引值,否则返回-1。

    def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.find(sub[, start[, end]]) -> int
        
        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.
        
        Return -1 on failure.
        """
        return 0
    

    index() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,该方法与 python find()方法一样,只不过如果str不在string中会报一个异常。

    def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.index(sub[, start[, end]]) -> int
        
        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0
    

    示例:

    s18 = 'yun tie Yumo'
    print(s18.find('ao'))
    print(s18.find('mo'))
    print(s18.find('i'))
    print(s18.index('tie', 3, -1))
    print(s18.index('i', 2))
    
    结果:
    -1
    10
    5
    4
    5
    

    9)count 计数,寻找元素出现的个数;

    S.count(sub[, start[, end]]) -> int
    记忆方法:count,计数器;常用变量名,常用函数方法。

    count() 方法用于统计字符串里某个字符出现的次数。
    可选参数为在字符串搜索的开始与结束位置。

     def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__
        """
        S.count(sub[, start[, end]]) -> int
        
        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are
        interpreted as in slice notation.
        """
        return 0
    

    示例:

    s18 = 'yun tie Yumo'
    print(s18.count('u'))
    
    结果:2
    

    10)replace 替换sub str;

    (很有用,比如某些情境下循环遍历非数字的字符替换成空格,再split分割就做出了全部纯数字的列表了。)

    S.replace(old, new[, count]) -> str
    记忆方法:replace,替代

    replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。

    def replace(self, old, new, count=None): # real signature unknown; restored from __doc__
        """
        S.replace(old, new[, count]) -> str
        
        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""
    

    示例:

    s18 = 'yun tie Yumo'
    s20 = s18.replace('Yu', 'M', 1)
    print(s20)
    
    结果:yun tie Mmo
    

    11)split 分割,重要程度5颗星。因为split比其它字符串操作方法都要神奇,别的是生成新的字符串,它是直接将字符串生成List(列表)了。而且运维操作日志方面也有常用到它的。

    S.split(sep=None, maxsplit=-1) -> list of strings (生成的是全是字符串元素组成的列表)
    记忆方法:split,分离。

    split()通过指定分隔符对字符串进行切片,如果参数num 有指定值,则仅分隔 num 个子字符串(可指定进行分割的次数)。默认以空格作为分隔符进行切片。另外要注意的是它以什么字符为分隔符,那指定的分隔符字符就会同时也被消除掉。此外若分隔符刚好在第一位,左边的没有字符了,仍然会生成空字符串。此外从右往左分割使用rsplit。

    def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__
        """
        S.split(sep=None, maxsplit=-1) -> list of strings
        
        Return a list of the words in S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are
        removed from the result.
        """
        return []
    

    示例:

    s18 = 'yun tie Yumo'
    s21 = s18.split()
    print(s21,type(s21))
    s22 = s18.split('u')
    print(s22)
    print(s18.split('y',1))
    
    效果:
    ['yun', 'tie', 'Yumo'] <class 'list'>
    ['y', 'n tie Y', 'mo']
    ['', 'un tie Yumo']
    

    12)join 加入、连接字符串;(建议和split成对记。)

    S.join(iterable) -> str
    记忆方法:join,连接(符);可以想像成它就是一座桥。

    join() 方法用于将序列中的元素以指定的字符连接生成一个新的字符串。
    它的源码说明文档中有iterable(可迭代的,可重复的)表示可对可迭代的对象进行操作;
    (self对象是'自己')

    另外在对一个列表中的众多字符串元素做拼接操作时,join 是一种更加高效的字符串连接方式,使用 + 操作时,每执行一次+操作就会导致在内存中生成一个新的字符串对象,遍历8次有8个字符串生成,造成无谓的内存浪费。而用 join 方法整个过程只会产生一个字符串对象。

    join不止能对字符串进行操作,还可对元祖/列表等操作,只不过进行操作时最好要确保列表中的所有元素都是字符串,不然有些列表操作会不成功。
    用某字符串做一个连接符,连接可迭代对象中的每一个元素,形成一个新的字符串。

    #迭代:对计算机特定程序中需要反复执行的子程序*(一组指令),进行一次重复,即重复执行程序中的循环,直到满足某条件为止,亦称为迭代。

    def join(self, iterable): # real signature unknown; restored from __doc__
        """
        S.join(iterable) -> str
        
        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""
    

    示例:

    s18 = 'yun tie Yumo'
    s21 = s18.split()
    print(s21,type(s21))
    s23 = '*'.join(s21)
    print(s23,type(s23))
    
    效果:
    (可以看到list转换成str了,且每个元素之间加上了自定义的*号连接符。)
    ['yun', 'tie', 'Yumo'] <class 'list'>
    yun*tie*Yumo <class 'str'>
    

    13)format 格式化函数,这里单单记录一下对字符串的格式化操作方法。

    S.format(*args, **kwargs) -> str
    记忆方法:format,格式化。

    它增强了字符串格式化的功能。
    基本语法是通过 {} 和 : 来代替以前的 % 。
    format 函数可以接受不限个参数,位置可以不按顺序。

    def format(self, *args, **kwargs): # known special case of str.format
        """
        S.format(*args, **kwargs) -> str
        
        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass
    

    示例1:

    s = "{} {}".format("hello", "tiele")  #不设置指定位置,按默认顺序
    print(s)  #显示hello tiele
    print("{0} {1}".format("hello", "tiele")) #指定索引位置输出
    
    print("我叫{0},我今年{1}岁,我热爱{2}。
    明年{1},我仍然是{0},我依然热爱{2}。".format("铁乐", "18", "运维开发"))
    # 多个位置对应一个索引位置格式化
    # 输出结果:
    我叫铁乐,我今年18岁,我热爱运维开发。明年18,我仍然是铁乐,我依然热爱运维开发。
    

    示例2:

    # 也可指定参数,下面是通过字典(键值对)指定参数的例子
    site = {"name": "铁乐与猫梦境之森", "url": "www.tielemao.com"}
    print("我的网站:{name}, 网址:{url}".format(**site))
    
    效果:
    我的网站:铁乐与猫梦境之森, 网址:www.tielemao.com
    
    # 通过列表索引设置参数
    my_list = ['铁乐与猫','www.tielemao.com', '运维人生']
    print("我的网站:{0[0]},网址:{0[1]}, 主题是:{0[2]}".format(my_list))
    #注:此处0不可省略,后面[]接的是列表中的索引位置。
    
    效果:
    我的网站:铁乐与猫,网址:www.tielemao.com, 主题是:运维人生
    

    14)判断字符串操作(返回布尔值)

    (很有用,在计算器,验证码之类的输入框中估计都能用到)

    以下三个一起记:
    isalnum() 方法检测字符串是否由字母和数字组成。
    isalpha() 方法检测字符串是否只由字母组成。
    isdigit() 方法检测字符串是否只由数字组成。

    记忆方法:alpha,阿尔法,字母狗;al+num,字母+数字;digit,数字,数脚趾。

    使用技巧:
    比如,if no str.isdigit() 则是判断除数字外的(包括特殊符号等情况)都在内了。
    而if str.isdigit() 则条件就是满足是数字。

    实例1:

    # 计算用户输入的内容中有几个整数(以个位数为单位)。
    num = 0
    content = input('请输入由字母和数字组成的内容:').strip()
    for i in content:
        if i.isdigit():
             num += 1
    print(num)
    
    实例2:
    # 计算用户输入的内容中有几个整数(以相连的数字为一个整数计数)。
    content = input('请输入:').strip()
    for i in content:
         # 判断i不为数字类型就用空格进行替换填充,
         # 注意这里最初我是用了判断是字母类型就进行空格填充,然后就出现了测试时输入特殊符号时计算错误
         # 所以有个原则是尽量用(not 真)的方式来包含不是你所求的范围。
         if not i.isdigit():
            content = content.replace(i, ' ', 1)
    # print(content)
    # 替换空格之后就可以利用split进行对空切割成列表,然后用len求出列表中的元素个数就得出整数个数结果了。
    print('你输入的内容中共有%s个整数。' % len(content.split()))
    

    End

  • 相关阅读:
    [deviceone开发]-echart的简单报表示例
    [deviceone开发]-do_GridView的简单示例
    [deviceone开发]-天气demo
    [deviceone开发]-QQ分享、微信分享和新浪微博分享
    [deviceone开发]-HeaderView和FooterView的示例
    [deviceone开发]-动画示例源码
    C#之文件的读写(一)
    try-catch-finally 用法
    C# datetime 格式化
    C#中foreach的用法
  • 原文地址:https://www.cnblogs.com/tielemao/p/8618354.html
Copyright © 2011-2022 走看看