In [2]:
import string
s = 'hello, i came from China University of Mining and technology'
print(s)
print(string.capwords(s))
In [3]:
import string
values = {'var':'foo'}
t = string.Template('''
Variable : $var
Escape : $$
Variable in text : ${var}iable
''')
print('Template:', t.substitute(values))
In [5]:
s = '''
variable : %(var)s
escape : %%
variable in text :%(var)siable
'''
print('Interploation', s % values)
In [7]:
s = '''
varibale : {var}
Escape : {{}}
Variable in text : {var}iable
'''
print('Fomat:', s.format(**values))
using safe_substitute method
In [8]:
import string
values = {'var':'foo'}
t = string.Template('$var is here but $missing is not provided')
print('safe_substitute', t.safe_substitute(values))
In [9]:
import string
class MyTemplate(string.Template):
delimiter = '%'
idpattern = '[a-z]+_[a-z]+'
template_text = '''
Delimiter : %%
Replaced : %with_underscore
Ignore : %notunderscores
'''
d = {
'with_underscore' : 'replaced',
'notunderscore' : 'not replaced'
}
t = MyTemplate(template_text)
print('Modified ID pattern')
print(t.safe_substitute(d))
In [10]:
import string
t = string.Template('$var')
print(t.pattern.pattern)
In [12]:
import re
import string
class MyTemplate(string.Template):
delimiter = '{{'
pattern = r'''
\{\{(?:
(?P<escaped>\{\{)|
(?P<named>[_a-z][_a-z0-9]*)\}\}|
(?P<braced>[_a-z][_a-z0-9]*)\}\}|
(?P<invalid>)
)
'''
t = MyTemplate('''
{{{{
{{var}}
''')
print('MATCHES:', t.pattern.findall(t.template))
print('Substitude:', t.safe_substitute(var='replacement'))
In [14]:
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))