美文网首页
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学习资料--字符串处理内置方法全集

    Python学习资料整理--字符串处理内置方法全集 代码小工蚁整理了python编程语言的字符串处理内置方法。欢迎...

  • Python3字符串处理函数

    Python3字符串处理函数 Python3

  • Python | 如何处理字符串过长

    标签:python 2019-01-28-如何处理字符串过长? 原网址: 在python中长度不建议超过80,处理...

  • PythonQuickView by L0st

    PythonQuickView 处理字符串 列表 数字相关 元组 Python中的逻辑运算 Python中的If结...

  • Python字符串处理的8招秘籍

    Python的字符串处理,在爬虫的数据解析、大数据的文本清洗,以及普通文件处理等方面应用非常广泛,而且Python...

  • Python 字符串常见操作总结

    介绍Python常见的字符串处理方式 1、字符串连接 2、字符串转数组 3、字符串比较 4、字符串查找 5、字符串...

  • Python字符串的处理

    平时使用Python都是处理一些脚本,其中使用频率最大的就是字符串的处理方面,因此整理一些常用的字符串处理使用方法...

  • 【Chapter 7.3】字符串处理

    【Chapter 7.3】字符串处理 python很多内建方法很适合处理string。而且对于更复杂的模式,可以配...

  • Python截取字符串的子串

    Python处理字符串非常方便。这篇博客将通过一个简单的示例程序介绍如何使用Python截取字符串的子串。 示例程...

  • python 字符串学习

    python 字符串的处理,可谓十分强大。是值得花费实际去学习的,作为运维之前使用的shell处理字符串,基本上自...

网友评论

      本文标题:Python字符串处理

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