Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String split formatting in python 3

I'm trying to format this string below where one row contains five words. However, I keep getting this as the output:

I love cookies yes I do Let s see a dog

First, I am not getting 5 words in one line, but instead, everything in one line.

Second, why does the "Let's" get split? I thought in splitting the string using "words", it will only split if there was a space in between?

Suggestions?

string = """I love cookies. yes I do. Let's see a dog."""


# split string
words = re.split('\W+',string)

words = [i for i in words if i != '']


counter = 0
output=''
for i in words:
    if counter == 0:
        output +="{0:>15s}".format(i)

# if counter == 5, new row
    elif counter % 5 == 0:
       output += '\n'
       output += "{0:>15s}".format(i)

    else:
       output += "{0:>15s}".format(i)

    # Increase the counter by 1
    counter += 1

print(output)
like image 246
Student J Avatar asked Jun 20 '13 19:06

Student J


Video Answer


2 Answers

As a start, don't call a variable "string" since it shadows the module with the same name

Secondly, use split() to do your word-splitting

>>> s = """I love cookies. yes I do. Let's see a dog."""
>>> s.split()
['I', 'love', 'cookies.', 'yes', 'I', 'do.', "Let's", 'see', 'a', 'dog.']

From re-module

\W Matches any character which is not a Unicode word character. This is the opposite of \w. If the ASCII flag is used this becomes the equivalent of [^a-zA-Z0-9_] (but the flag affects the entire regular expression, so in such cases using an explicit [^a-zA-Z0-9_] may be a better choice).

Since the ' is not listed in the above, the regexp used splits the "Let's" string into two parts:

>>> words = re.split('\W+', s)
>>> words
['I', 'love', 'cookies', 'yes', 'I', 'do', 'Let', 's', 'see', 'a', 'dog', '']

This is the output I get using the strip()-approach above:

$ ./sp3.py 
              I           love       cookies.            yes              I
            do.          Let's            see              a           dog.

The code could probably be simplified to this since counter==0 and the else-clause does the same thing. I through in an enumerate there as well to get rid of the counter:

#!/usr/bin/env python3

s = """I love cookies. yes I do. Let's see a dog."""
words = s.split()

output = ''
for n, i in enumerate(words):
    if n % 5 == 0:
        output += '\n'
    output += "{0:>15s}".format(i)
print(output)
like image 175
Fredrik Pihl Avatar answered Oct 18 '22 21:10

Fredrik Pihl


words = string.split()
while (len(words))
     for word in words[:5]
          print(word, end=" ")
     print()
     words = words[5:]

That's the basic concept, split it using the split() method

Then slice it using slice notation to get the first 5 words

Then slice off the first 5 words, and loop again

like image 30
Stephan Avatar answered Oct 18 '22 20:10

Stephan