美文网首页
Python字符串处理

Python字符串处理

作者: quchangTJU | 来源:发表于2019-07-06 17:42 被阅读0次

    导入string模块

    # coding=utf-8
    import string
    

    每个单词首字母大写

    print string.capwords('He is a teacher.')
    # >>>He Is A Teacher.
    

    替换字符串中的字符

    s1 = string.maketrans('abc', '123')
    s2 = 'abcabcabc'
    print s2.translate(s1)
    # 123123123
    

    字符串模板

    values = {'name': 'Tom'}
    t = string.Template("""
    1.他的名字是:$name
    2.输出美元符号:$$
    3.${name}是个好同志
    """)
    print t.safe_substitute(values)
    # 1.他的名字是:Tom
    # 2.输出美元符号:$
    # 3.Tom是个好同志
    

    高级字符串模板

    s1 = '''
    输出百分号:%%
    中间有_的变量会被替换掉:%abc_abc
    中间没有_的变量不会被替换:%abcabc
    '''
    values = {'abc_abc': '被替换',
              'abcabc': '不会被替换'}
    
    
    class MyTemplate(string.Template):
        # 新建模板类继承自string.Template
        delimiter = '%'
        # %符号为匹配字符
        idpattern = '[a-z]+_[a-z]+'
        # 设置匹配模式,只有中间有_的变量会被匹配
    
    
    t = MyTemplate(s1)
    print t.safe_substitute(values)
    # 输出百分号:%
    # 中间有_的变量会被替换掉:被替换
    # 中间没有_的变量不会被替换:%abcabc
    

    调整字符串的缩进、宽度

    import textwrap
    
    s1 = '''
    Every parent will worry about their children, 
    so they teach the children many things, 
    just in case they will meet the bad guy. 
    My mother always tells me not to talk 
    to the strangers or accept the food from them, 
    or I may never see them again. 
    I keep her words in mind, so I can avoid the potential dangers. 
    '''
    
    s2 = textwrap.dedent(s1.strip())  # 去掉字符串前后空格,并且字符串向左移
    print textwrap.fill(s2,
                        70,  # 调整每行宽度
                        initial_indent='',  # 初始缩进
                        subsequent_indent=' ' * 4  # 后面行缩进
                        )
    # Every parent will worry about their children,  so they teach the
    #     children many things,  just in case they will meet the bad guy.
    #     My mother always tells me not to talk to the strangers or accept
    #     the food from them,  or I may never see them again. I keep her
    #     words in mind, so I can avoid the potential dangers.
    

    相关文章

      网友评论

          本文标题:Python字符串处理

          本文链接:https://www.haomeiwen.com/subject/gkophctx.html