Search code examples
pythonenter

Add an enter to string every 22 characters, waiting until a space


I am trying to get my code to insert a \n into my code every 22 characters, but if the 22nd character is not a space it waits till there is one then inserts the \n there.

I have tried looking up some code for the past hour on StackOverflow, but most seem to break with some changes, because they where specifically made for that problem.

Here is some code I have tried

count = 0
s = "I learned to recognise the through and primitive duality of man; I saw that, of the two natures that contended in the field of my consciousness, even if I could rightly be said to be either, it was only because I was radically both"
newS = ""
enterASAP = False
while True:
    count += 1
    if enterASAP == True and s[count-1] == " ":
        newS = (s[:count] + "\n" + s[count:])
    if count % 22 == 0:
        if s[count-1] == " ":
            newS = (s[:count] + "\n" + s[count:])
        else:
            enterASAP = True
    if count == len(s):
        print(newS)
        print("Done")
        break

I am wanting it to produce a text like
I learned to recognise the thorough and primitive
.......
Note that it waits for the space and then the count resets at from the to primitive rather than adding on the 5 extra letters that the code waited for the space.

The code that I have produces the exact string it starts with. Which baffles me


Solution

  • As discussed in the comments, the version with textwrap (doc):

    import textwrap
    
    s = "I learned to recognise the through and primitive duality of man; I saw that, of the two natures that contended in the field of my consciousness, even if I could rightly be said to be either, it was only because I was radically both"
    
    print('\n'.join(textwrap.wrap(s, 22)))
    

    Prints:

    I learned to recognise
    the through and
    primitive duality of
    man; I saw that, of
    the two natures that
    contended in the field
    of my consciousness,
    even if I could
    rightly be said to be
    either, it was only
    because I was
    radically both