Friday 15 February 2013

String split formatting in python 3 -


I am trying to format this string below, where there are five words in a row, however, I'm getting into:

I like cookies Yes I do see a dog

First of all, I can not find 5 words. In line, but instead, everything in one line

Second, why get "let" partition? I thought of dividing the string using "words", if it was a space in the middle, would it be divided only?

Suggestions? "I love cookies, yes, I see a dog." ############ If I In Words! = ''] Counter = 0 Output = '' for words in: if counter == 0: Output + = "{0: & gt; 15s}". Format (i) # if counter == 5, New line alip counter% 5 == 0: Output + = '\ n' Output + = "{0: & gt; 15s}". Format (i) Other: Output + = "{0: & gt; 15s}" format (i) # counter 1 counter + = increase from print (output)

As a beginner, do not call a variable "string" because it shadows with the same name

  & gt; & Gt; & Gt; S = "" "I love cookies. Yeah, I see a dog." "" & Gt; & Gt; & Gt; S.) () "I", "Love", "Cookies", "Yes", "I", "Do", "Walk", "Watch", "A", "Dog".)   

to

\ w matches any letter which is not a Unicode word character. This is the opposite of \ w if the ASCII flag is used then it is equivalent to [^ a-zA-Z0- 9_] (but the flag affects the whole regular expression, so in these cases obvious [^ a] -zA-Z0-9_] might be a better option).

Since ' is not listed above, regexp split the "Walk" string into two parts:

  & gt; & Gt; & Gt; Word = re.split ('\ w +', s)> gt; & Gt; & Gt; Word '[' I ',' love ',' cookies ',' yes ',' i ',' do ',' go ',' s ',' see ',' a ',' dog ',' / code >  

This is the output using the out strip () - approach:

  $ ./sp3.py I like cookies I do this Let's look at a dog   

The code may be simplified for it because the counter == 0 and the second clause does the same thing. I'm also there to get rid of:

  #! / Usr / bin / env python3 s = "" I like cookies. "" Word "= s.split () for output = '', I am in enumerate (if): if n% 5 == 0: Output + = '\ n' Output + = "{0: & gt; 15s}". Format (i) Print (Output)    

No comments:

Post a Comment