Problem: Merging many small strings into one large string
Solution:
1, for a small number of strings: +
2. A more efficient way to connect to a large number of String objects: Join ()
3. More complex Strings: 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?
A tip: Use a builder expression to complete a JOIN operation while converting data to a string
>>> data=['aqsc', 50,91.2]','for in data)'aqsc,50,91.2'
Last but not least, if we write code to build output from many short strings, you should consider writing generator functions to generate a string fragment from the yield keyword;
#example.py##Example of combining text via generatorsdefsample ():yield " is" yield "Chicago" yield " not" yield "Chicago?"#(a) use Join () to simply connect them togetherText ="'. Join (sample ())Print(text)Print('======================')#(b) Redirect these fragments to I/OImportSYS forPartinchsample (): Sys.stdout.write (part) Sys.stdout.write ('\ n')Print('**************************')#(c) intelligently combine I/O operations in a mixed mannerdefCombine (source, maxsize): Parts=[] Size=0 forPartinchsource:parts.append (part) Size+=Len (part)ifSize >maxsize:yield "'. Join (parts) parts=[] Size=0yield "'. Join (Parts) forPartinchCombine (sample (), 32768): Sys.stdout.write (part) Sys.stdout.write ('\ n')
>>> ================================ RESTART ================================>>> Ischicagonotchicago? ======================Ischicagonotchicago? Ischicagonotchicago?
"Python Cookbook" "String and Text" 14. String joins and merges