Splitting a variable-length string into several parts in python

I have a database:

As you can see in the β€œdesc” column, the text has a variable length (this means that the two rows that I extract from this database will have the same length). As a result, I will add many more entries to this database, but with this I am testing and starting from now on.

Right now I have the following python code to capture 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:]) 

Separation here works to some extent, for example:

Command: close:
Description: This command will create "close", but for
n in the message box to call char
Acter. If there is currently no window on the screen, t
he will finish the execution of the script.

As you can see in the example above in the output, the separation causes some characters to be cut off in the middle of the word. Given the fact that lines can have any length between words ... 20 total characters and up to 190ish, and I want to split the line into pieces, say ... 8 words due to space limitations, how would I go about this?

+6
source share
3 answers

Divide individual words into spaces, and then combine 8 at a time with a space as a 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 
+2
source

Open the text print 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 great customization of TextWrapper.

+16
source

Cut with 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 >>> 
+1
source

Source: https://habr.com/ru/post/906060/


All Articles