Jguy
Jguy

Reputation: 580

Splitting a variable length string into multiple parts in python

I have a database:

As you can see in the 'desc' column, the text is of variable length (meaning no two strings I pull from this database are going to be of the same length). I will eventually add many more entries to this database, but this is what I'm testing with and starting with at the moment.

Right now, I have the following python code to grab these blocks of string and display them:

cmd = input(Enter command:)
sql = "SELECT cmd,`desc` FROM table WHERE cmd = '"+ cmd +"'"
cursor.execute(sql)
result = cursor.fetchall()
for row in result:
    print("Command: "+ row[0] +":\n")
    print("Description: "+ row[1][:40] +"\n")
    if (len(row[1]) > 40):
       print(row[1][40:85])
    if (len(row[1]) > 85):
       print(row[1][85:130])
    if (len(row[1]) > 130):
       print(row[1][130:165])
    if (len(row[1]) > 165):
       print(row[1][165:])

The splitting here works to an extent, for example:

Command: close:
Description: This command will create a 'close' butto
n in the message window for the invoking char
acter. If no window is currently on screen, t
he script execution will end.

As you can see with the example above of the output, the split causes some characters to get cut off in mid word. Given the fact that the strings could be of any length between say...20 total characters and up to 190ish, and I want to split the string into chunks of say...8 words each because of space constraints, how would I go about doing this?

Upvotes: 7

Views: 6626

Answers (3)

joaquin
joaquin

Reputation: 85613

Cut by words instead of characters using python textwrap module:

>>> import textwrap
>>> text = 'asdd sdfdf asdsg asfgfhj'
>>> s = textwrap.wrap(text, width=10)  # <- example 10 characters
>>> s
['asdd sdfdf', 'asdsg', 'asfgfhj']
>>> print '\n'.join(s)
asdd sdfdf
asdsg
asfgfhj
>>> 

Upvotes: 1

DSM
DSM

Reputation: 353049

Check out the textwrap module.

>>> import textwrap
>>> 
>>> s = "This command will create a 'close' button in the message window for the invoking character. If no window is currently on screen, the script execution will end."
>>> 
>>> wrapped = textwrap.wrap(s, 40)
>>> 
>>> for line in wrapped:
...     print line
... 
This command will create a 'close'
button in the message window for the
invoking character. If no window is
currently on screen, the script
execution will end.

You can do a lot of configuration of TextWrapper.

Upvotes: 16

JustinDanielson
JustinDanielson

Reputation: 3185

Split on spaces to separate words, then join 8 at a time with a space as the separator.

content = "This is some sentence that has more than eight words"
content = content.split(" ")
print content
['This', 'is', 'some', 'sentence', 'that', 'has', 'more', 'than', 'eight', 'words']
print(" ".join(content[0:8]))
This is some sentence that has more than

Upvotes: 2

Related Questions