string 字符串模塊操做

1. 經常使用方法python

 

 

 

2.字符串常量git

 

 

 

 

3.字符串模板Templategithub

 

經過string.Template能夠爲Python定製字符串的替換標準,下面是具體列子:sql

 

>>>from string import Template.net

>>>s = Template('$who like $what')blog

>>>print s.substitute(who='i', what='python')繼承

i like python內存

 

>>>print s.safe_substitute(who='i') # 缺乏key時不會拋錯字符串

i like $whatunderscore

 

>>>Template('${who}LikePython').substitute(who='I') # 在字符串內時使用{}

'ILikePython'

 

Template還有更加高級的用法,能夠經過繼承string.Template, 重寫變量delimiter(定界符)和idpattern(替換格式), 定製不一樣形式的模板。

 

import string

 

template_text = ''' Delimiter : $de Replaced : %with_underscore Ingored : %notunderscored '''

 

d = {'de': 'not replaced',

     'with_underscore': 'replaced',

     'notunderscored': 'not replaced'}

 

class MyTemplate(string.Template):

    # 重寫模板 定界符(delimiter)爲"%", 替換模式(idpattern)必須包含下劃線(_)

    delimiter = '%'

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

 

print string.Template(template_text).safe_substitute(d)  # 採用原來的Template渲染

 

print MyTemplate(template_text).safe_substitute(d)  # 使用重寫後的MyTemplate渲染

 

輸出:

 

Delimiter : not replaced

    Replaced : %with_underscore

    Ingored : %notunderscored

 

    Delimiter : $de

    Replaced : replaced

    Ingored : %notunderscored

 

原生的Template只會渲染界定符爲$的狀況,重寫後的MyTemplate會渲染界定符爲%且替換格式帶有下劃線的狀況。

 

4.經常使用字符串技巧

 

1.反轉字符串

 

>>> s = '1234567890'

>>> print s[::-1]

0987654321

 

2.關於字符串連接

 

儘可能使用join()連接字符串,由於’+’號鏈接n個字符串須要申請n-1次內存,使用join()須要申請1次內存。

 

3.固定長度分割字符串

 

>>> import re

>>> s = '1234567890'

>>> re.findall(r'.{1,3}', s)  # 已三個長度分割字符串

['123', '456', '789', '0']

 

4.使用()括號生成字符串

 

sql = ('SELECT count() FROM table '

       'WHERE id = "10" '

       'GROUP BY sex')

 

print sql

 

SELECT count() FROM table WHERE id = "10" GROUP BY sex

———————————————— 版權聲明:本文爲CSDN博主「yolosliu」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處連接及本聲明。原文連接:https://blog.csdn.net/github_36601823/article/details/77815013

相關文章
相關標籤/搜索