def tag(name, *content, cls=None, **attrs):
if cls is not None:
attrs[‘class‘] = cls
if attrs:
attr_str = ‘‘.join(‘ %s="%s"‘ % (attr,value ) for attr, value in sorted(attrs.items()))
else:
attr_str = ‘‘
if content:
value=‘\n‘.join(‘<%s%s>%s</%s>‘ % (name,attr_str,c,name) for c in content)
return value
else:
value= ‘<{}{} />‘.format(name, attr_str)
return value
print(tag(‘br‘))
print(tag(‘p‘,‘hello‘))
print(tag(‘P‘,‘hello‘,id=33))
print(tag(‘p‘,‘hello‘,‘world‘,cls=‘sidebar‘))
print(tag(content=‘testing‘,name=‘img‘))
my_tag={‘name‘:‘img‘,‘title‘:‘subtitle‘,‘src‘:‘sunset.img‘,‘cls‘:‘framed‘}
print(tag(**my_tag))#字典中所有元素作为单个参数传入
原文:https://www.cnblogs.com/xuyuchen/p/12266755.html