当前位置: 首页 > news >正文

上海装修公司网站建设/橘子seo查询

上海装修公司网站建设,橘子seo查询,大连做外贸建站的专业公司,运营网站开发工作string—文本常量和模板作用:包含处理文本的常量和类。Python版本:1.4及以后版本最早的Python版本就有string模块。 之前在这个模块中实现的许多函数已经移至str对象的方法。 string模块保留了几个有用的常量和类,用于处理str对象。函数capwo…

string—文本常量和模板

作用:包含处理文本的常量和类。

Python版本:1.4及以后版本

最早的Python版本就有string模块。 之前在这个模块中实现的许多函数已经移至str对象的方法。 string模块保留了几个有用的常量和类,用于处理str对象。

函数

capwords()的将字符串中所有单词的首字母大写。

#!python

>>> import string

>>> t = "hello world!"

>>> string.capwords(t)

'Hello World!'

>>> t

'hello world!'

>>> t.capitalize()

'Hello world!'

>>> t

'hello world!'

结果等同于先调用split(),把结果列表中各个单词的首字母大写,然后调用join()合并结果。

因为str对象已经有capitalize()方法,该函数的实际意义并不大。

模板

字符串模板已经作为PEP 292的一部分增加到Python 2.4中,并得到扩展,以替代内置拼接(interpolation)语法类似。使用string.Template拼接时,可以在变量名前面加上前缀$(如$var)来标识变量,如果需要与两侧的文本相区分,还可以用大括号将变量括起(如${var})。

下面的例子对简单的模板和使用%操作符及str.format()进行了比较。

#!python

import string

values = {'var': 'foo'}

t = string.Template("""

Variable : $var

Escape : $$

Variable in text: ${var}iable

""")

print('TEMPLATE:', t.substitute(values))

s = """

Variable : %(var)s

Escape : %%

Variable in text: %(var)siable

"""

print('INTERPOLATION:', s % values)

s = """

Variable : {var}

Escape : {{}}

Variable in text: {var}iable

"""

print('FORMAT:', s.format(**values))

"""

print 'INTERPOLATION:', s % values

执行结果:

#!python

python3 string_template.py

TEMPLATE:

Variable : foo

Escape : $

Variable in text: fooiable

INTERPOLATION:

Variable : foo

Escape : %

Variable in text: fooiable

FORMAT:

Variable : foo

Escape : {}

Variable in text: fooiable

模板与标准字符串拼接的重要区别是模板不考虑参数类型。模板中值会转换为字符串且没有提供格式化选项。例如没有办法控制使用几位有效数字来表示浮点数值。

通过使用safe_substitute()方法,可以避免未能提供模板所需全部参数值时可能产生的异常。

tring_template_missing.py

#!python

import string

values = {'var': 'foo'}

t = string.Template("$var is here but $missing is not provided")

try:

print('substitute() :', t.substitute(values))

except KeyError as err:

print('ERROR:', str(err))

print('safe_substitute():', t.safe_substitute(values))

由于values字典中没有对应missing的值,因此substitute()会产生KeyError。不过,safe_substitute()不会抛出这个错误,它将捕获这个异常,并在文本中保留变量表达式。

#!python

$ python3 string_template_missing.py

ERROR: 'missing'

safe_substitute(): foo is here but $missing is not provided

高级模板(非常用)

可以修改string.Template的默认语法,为此要调整它在模板体中查找变量名所使用的正则表达式模式。简单的做法是修改delimiter和idpattern类属性。

string_template_advanced.py

#!python

import string

class MyTemplate(string.Template):

delimiter = '%'

idpattern = '[a-z]+_[a-z]+'

template_text = '''

Delimiter : %%

Replaced : %with_underscore

Ignored : %notunderscored

'''

d = {

'with_underscore': 'replaced',

'notunderscored': 'not replaced',

}

t = MyTemplate(template_text)

print('Modified ID pattern:')

print(t.safe_substitute(d))

执行结果:

#!python

$ python3 string_template_advanced.py

Modified ID pattern:

Delimiter : %

Replaced : replaced

Ignored : %notunderscored

默认模式

#!python

>>> import string

>>> t = string.Template('$var')

>>> print(t.pattern.pattern)

\$(?:

(?P\$) | # Escape sequence of two delimiters

(?P(?-i:[_a-zA-Z][_a-zA-Z0-9]*)) | # delimiter and a Python identifier

{(?P(?-i:[_a-zA-Z][_a-zA-Z0-9]*))} | # delimiter and a braced identifier

(?P) # Other ill-formed delimiter exprs

)

string_template_newsyntax.py

#!python

import re

import string

class MyTemplate(string.Template):

delimiter = '{{'

pattern = r'''

\{\{(?:

(?P\{\{)|

(?P[_a-z][_a-z0-9]*)\}\}|

(?P[_a-z][_a-z0-9]*)\}\}|

(?P)

)

'''

t = MyTemplate('''

{{{{

{{var}}

''')

print('MATCHES:', t.pattern.findall(t.template))

print('SUBSTITUTED:', t.safe_substitute(var='replacement'))

执行结果:

#!python

$ python3 string_template_newsyntax.py

MATCHES: [('{{', '', '', ''), ('', 'var', '', '')]

SUBSTITUTED:

{{

replacement

格式化

Formatter类实现与str.format()类似。 其功能包括类型转换,对齐,属性和字段引用,命名和位置模板参数以及特定类型的格式选项。 大多数情况下,fformat()方法是这些功能的更方便的接口,但是Formatter是作为父类,用于需要变化的情况。

常量

string模块包含许多与ASCII和数字字符集有关的常量。

string_constants.py

#!python

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

# Author: xurongzhong#126.com wechat:pythontesting qq:37391319

# 技术支持 钉钉群:21745728(可以加钉钉pythontesting邀请加入)

# qq群:144081101 591302926 567351477

# CreateDate: 2018-6-12

import inspect

import string

def is_str(value):

return isinstance(value, str)

for name, value in inspect.getmembers(string, is_str):

if name.startswith('_'):

continue

print('%s=%r\n' % (name, value))

执行结果

#!python

$ python3 string_constants.py

ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

ascii_lowercase='abcdefghijklmnopqrstuvwxyz'

ascii_uppercase='ABCDEFGHIJKLMNOPQRSTUVWXYZ'

digits='0123456789'

hexdigits='0123456789abcdefABCDEF'

octdigits='01234567'

printable='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

punctuation='!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

whitespace=' \t\n\r\x0b\x0c'

参考资料

讨论 钉钉免费群21745728 qq群144081101 567351477

String Methods – Methods of str objects that replace the deprecated functions in string.

PEP 292 – Simpler String Substitutions

Format String Syntax – The formal definition of the layout specification language used by Formatter and str.format().

http://www.jmfq.cn/news/4895497.html

相关文章:

  • 重庆找工作哪个网站好/巨量关键词搜索查询
  • wordpress 扫描工具/上海aso优化公司
  • 电子商务网站建设计划书/建网站建设
  • 网站前置审批怎么做/网络营销推广合作
  • 众筹网站建设/关键词歌词打印
  • 西部网站管理助手/百度认证证书
  • 网站中怎么插入flash/sem广告投放是做什么的
  • 做货代哪个网站上好找客户/百度一下 你知道首页
  • 注册门户网站/网站优化排名软件
  • 深圳 旅游 网站建设/网络营销收获与体会
  • 做企业展示版网站贵吗/做百度关键词排名的公司
  • 做网站域名后缀选择/电商平台运营方案思路
  • 做网络私活的网站/核心关键词如何优化
  • 如何写代码做网站/营业推广方案
  • 网站建设合同标准版/站长之家音效
  • 整站seo哪家服务好/推广平台 赚佣金
  • 做程序开发的网站/百度seo学院
  • html5购物网站模板/搭建网站工具
  • 台州做网站是什么/关于seo如何优化
  • 做职业规划的网站/免费获客软件
  • 郑州网站南京网站建设/免费建站网站大全
  • 织梦网站模板免费/品牌宣传方式
  • 深圳龙岗区最新疫情最新消息/seo技术代理
  • 传奇版本网页游戏/seo门户网站优化
  • 手机网站如何做才能兼容性各种手机/google 推广优化
  • 美食网站代做/长尾关键词挖掘站长工具
  • 工程项目管理软件app/苏州seo网络推广
  • 网站关键字优化公司/专业网站快速
  • 长沙建设公司网站/小程序搭建
  • 找外贸客户的网站/网络推广工作能长久吗