Skip to content
Advertisement

String handling in Python

I am trying to write a short python function to break a long one_line string into a multi_line string by inserting n. the code works fine when i simply insert n into the string but i get an index out of range error when i insert a conditional check to add hyphenation as well. Here is the code that i have written.

JavaScript

Here is the error message i get.

JavaScript

Advertisement

Answer

The conditional expression is greedy, parsed as if you had written

JavaScript

As a result, you are doing one of two operations:

  1. Sentence[:x] + 'n' if you find a space
  2. Sentence[:x] + "-n" + Sentence[x:] if you find a different character.

Note that case 1 shortens your sentence incorrectly, but your range object is based on the original correct list.

The solution is to use parentheses to define the conditional expression correctly:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement