Sar17
Sar17

Reputation: 35

How to put part of a string on a newline based on a given number? (Ignoring the spaces)

T = 7
string = "this is a string"

How do I put a part of the string on a new line, after 7 "lengths"? Also I don't want to include spaces as a character. It should print out:

this is a  < -- length = 7 (You don't need to print the < -- length = 7, it's just giving detail)
string  <-- The rest of the lines should not go over 7 characters, and should not break part words
that is 
very 
cool 

I was thinking of using a while loop:

while len(string)>T:
    # keep cutting off by 7`

Sorry, I'm new to Stack Overflow, so please excuse the way my question is formatted/written for now.

Upvotes: 0

Views: 230

Answers (6)

Benjamin Basmaci
Benjamin Basmaci

Reputation: 2557

I first split the string. Then I check for each word if that would exceed the 7 character limit T if so, add a newline before adding that word to the output. If not, add a space (except for the first word, as we don't want the output to start with a space. That should do it.

mystring = "this is a string"

substrings=mystring.split()

T = 7
i = 0
charCount = 0
output=""

print substrings

while(i < len(substrings)):
    charCount += len(substrings[i])
    if(charCount > T):
        output+="\n"
    elif(i != 0):
        output+=" "

    output+=substrings[i]
    i += 1

print output

Upvotes: 1

YFrog
YFrog

Reputation: 109

For another method, you can use a for loop with modulo 7

a = "..."
for i in range(len(a) // 7):
    print(a[7*i:7*i+7])

Upvotes: 0

ProteinGuy
ProteinGuy

Reputation: 1942

You can also use a list comprehension to split string into a list of strings.

string_ = 'The Quick Brown Fox Jumps Over the Lazy Dog'
T = 7
list_of_strings = [string_[T*i : T*(i+1)] for i in range(int(len(string_)/T + 1))]

for new_string in list_of_strings:
    print(new_string)

Output:

The Qui
ck Brow
n Fox J
umps Ov
er the 
Lazy Do
g

If you want to exclude gaps, use the .replace method to remove gaps.

string_ = 'The Quick Brown Fox Jumps Over the Lazy Dog'
string_nogaps = string_.replace(' ', '')
T = 7
list_of_strings = [string_nogaps[T*i : T*(i+1)] for i in range(int(len(string_nogaps)/T + 1))]

for new_string in list_of_strings:
    print(new_string)

Output:

TheQuic
kBrownF
oxJumps
Overthe
LazyDog

Upvotes: 0

L3viathan
L3viathan

Reputation: 27283

All other solutions I've tried got awkward the moment I started handling the spaces "properly", so I present: a regular expression!

>>> import re
>>> string = "the quick brown fox jumps over the lazy doggie"
>>> pattern = r"\S(?:\s*\S){6}|(?:\S\s*){,6}$"
>>> for match in re.findall(pattern, string):
...     print(match)
the quic
k brown f
ox jumps
over the
lazy dog
gie

We only count non-spaces as characters (meaning our strings are typically longer than 7 characters), and spaces are effectively stripped from the edges of the matches.

Here's how the pattern works:

\S(?:\s*\S){6}|(?:\S\s*){,6}$    Match either:
\S                               - a non-space character
  (       ){6}                     followed by six times:
   ?:                              (non-capturing)
     \s*\S                         any amount of spaces, and _one_ non-space
              |                  OR
               (?:     ){,6}     - _up to_ six times:
                  \S\s*            a non-space and any amount of spaces,
                            $      but only if we're at the end of the string

Upvotes: 1

Jongware
Jongware

Reputation: 22457

There are a lot of methods to do this. Incrementing a cursor position is one:

text = "this is a very long string to prove it actually works"
cursor = 0
T = 7
while cursor < len(text):
    print (text[cursor:cursor+T])
    cursor += T

As you apparently want to ignore counting spaces, though, a straight text slice cannot process that anymore and you will have to count each separate (printing) character. If you don't want to start printing a space, it also needs an additional check if printing 7 characters did not end up on a space itself.

T = 7
cursor = 0
while cursor < len(text):
    count_non_space = 0
    while count_non_space < T and cursor < len(text):
        print (text[cursor],end='')
        count_non_space += not(text[cursor].isspace())
        cursor += 1
    while cursor < len(text) and text[cursor] == ' ':
        print (text[cursor],end='')
        cursor += 1
    print ()

which results in

this is a 
very lon
g string 
to prove 
it actua
lly work
s

By the way, do not use the name string for a variable.

Upvotes: 2

Charlie Martin
Charlie Martin

Reputation: 112366

This is actualy pretty easy:

string = "this is a string"
newString = string[:7]+"\n"+string[7:]

string[:7] is the string up to but not including the seventh character '"\n"is the newline character string[7:]` is the string from the seventh character to the end.

Read about "slices" on strings.

Upvotes: 0

Related Questions