A few hours ago, I was porting a two-year-old Bash script into Python code and I encountered a task I believed I had never done before: splitting text into equal length strings.
If you read it, can you guess what I was trying to do? Here is a hint, a command I used in the Bash script: fold.
I needed text wrapping, simply as that, but if you are coding with Pythonic in mind, there doesn’t seem to be an elegant way to split a string into chucks. A few searches, I got two questions:
- What’s the best way to split a string into fixed length chunks and work with them in Python?
- Split python string every nth character?
I didn’t even read them, those codes are too ugly — not literally — to read. So I thought to myself, this can’t be right. There must be a better way to do. At the time, my mind was filled with the task in description, all I had was the word split.
Bringing up the shell script, then fold came to say hi to me again. That’s it! I realized that I was asking the wrong question and there was no way on Earth that Python didn’t have an elegant solution. At that point, I actually had something in my mind, because I knew I had came across a standard library, but I still went ahead and asked the right question:
fold text in python
The first one was what I knew it would be, the textwrap library, already in Python’s standard libraries.
This experience reminded me of an old guideline I read long time ago, Describe the goal, not the step of How To Ask Questions The Smart Way by Eric Steven Raymond.
When we ask a question, we tend to think as long as my problem is solved, then I can achieve the goal. However, sometimes you just pick wrong problem to solve.
After I correctly solved my issue, I went to search on those two Stack Overflow questions. Guess what, none of them has actually asked the OP the purpose and even thought about it might just about text wrapping, which I do believe the fundamentally they were.
Using textwrap not only resolving the splitting part but also the indentation, the split text would have to be indented by 4 spaces, with the library, which also have the indentation options. Just one call, an elegant solution.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.