标签:
问题:将许多小字符串合并成一个大的字符串
解决方案:
1、针对少数量的字符串:+
2、针对大量的字符串对象的连接,更高效的方法:join()
3、更加复杂的字符串:format()
>>> parts=[‘Is‘,‘Chicago‘,‘Not‘,‘Chicago?‘] >>> ‘,‘.join(parts) ‘Is,Chicago,Not,Chicago?‘ >>> a=‘Is Chicago‘ >>> b=‘Not Chicago?‘ >>> ‘{} {}‘.format(a,b) ‘Is Chicago Not Chicago?‘ >>> ‘{}{}‘.format(a,b) ‘Is ChicagoNot Chicago?‘ >>> ‘{}*{}‘.format(a,b) ‘Is Chicago*Not Chicago?‘ >>> ‘{}*&%${}‘.format(a,b) ‘Is Chicago*&%$Not Chicago?‘ >>> a+‘ ‘+b ‘Is Chicago Not Chicago?‘ >>> ‘Hello‘ ‘World‘ ‘HelloWorld‘ >>> print (a,b,sep=‘:‘) #更好的使用方法
Is Chicago:Not Chicago?
一个技巧:利用生成器表达式在将数据转换为字符串的同时完成连接操作
>>> data=[‘AQSC‘,50,91.2] >>> ‘,‘.join(str(d) for d in data) ‘AQSC,50,91.2‘ >>>
最后,但也是最重要的是,若我们编写的代码要从许多短字符串中构建输出,则应考虑编写生成器函数,通过yield关键字生成字符串片段;
# example.py # # Example of combining text via generators def sample(): yield "Is" yield "Chicago" yield "Not" yield "Chicago?" # (a) 使用join()将他们简单的连接起来 text = ‘‘.join(sample()) print(text) print(‘======================‘) # (b) 将这些片段重定向到I/O import sys for part in sample(): sys.stdout.write(part) sys.stdout.write(‘\n‘) print(‘**************************‘) # (c) 以混合的方式将I/O操作智能化地结合在一起 def combine(source, maxsize): parts = [] size = 0 for part in source: parts.append(part) size += len(part) if size > maxsize: yield ‘‘.join(parts) parts = [] size = 0 yield ‘‘.join(parts) for part in combine(sample(), 32768): sys.stdout.write(part) sys.stdout.write(‘\n‘)
>>> ================================ RESTART ================================ >>> IsChicagoNotChicago? ====================== IsChicagoNotChicago? ************************** IsChicagoNotChicago? >>>
【python cookbook】【字符串与文本】14.字符串连接及合并
标签:
原文地址:http://www.cnblogs.com/apple2016/p/5793427.html