"Python Cookbook" "String and Text" 14. String joins and merges

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.