Home > Enterprise >  How do you split a long string into two smaller strings, about the space character closest to the st
How do you split a long string into two smaller strings, about the space character closest to the st

Time:10-01

Suppose I have some string

str_0 = "This is a very long string that I would like to split into two shorter strings"

Is there a way that I can split this string into two based on the " " (space) character closest to the center? In the case of this string I would have

str_1 = "This is a very long string that I would"
str_2 = "like to split into two shorter strings"

CodePudding user response:

The question is not complete in the sense that a symmetric sentance would require a choice. For example how are you has two equal spaces either side of the 'middle'.

If the choice for a symmetric find is the first space, then you can split like this:

str_0="This is a very long string that I would like to split into two shorter strings"


def split_string(str_0):
    ''' function to split string by closest space'''

    mid_point = int(len(str_0)/2)

    if str_0[mid_point]==' ':
        # the middle point is a space
        str_1 = str_0[:mid_point]
        str_2 = str_0[mid_point 1:]
        return str_1, str_2


    for i in range(1,mid_point):
        # the middle point is a character
        if str_0[mid_point-i] == ' ':
            break_point = mid_point-i
            break

        if str_0[mid_point i] == ' ':
            break_point = mid_point i
            break

    str_1 = str_0[:break_point]
    str_2 = str_0[break_point 1:]
    return str_1, str_2


r = split_string(str_0)
print(r[0])
print(r[1])


the result is this:

This is a very long string that I would
like to split into two shorter strings

CodePudding user response:

Find the index of the character in the middle, then advance the index until you find a space. Finally, slice your string.

i = len(str_0) // 2
while str_0[i] != ' ':
    i  = 1

str_1 = str_0[:i]
str_2 = str_0[i 1:]

Note that this does not actually get the space closest to the center. Rather it grabs the first space at or after the midpoint. If that's an actual requirement use textwrap.wrap():

import textwrap

width = len(s) // 2
while len(result:=textwrap.wrap(s, width)) > 2:
    width  = 1

CodePudding user response:

I would try something like this:

>>> str_0 = "This is a very long string that I would like to split into two shorter strings"
>>> words = str_0.split()
>>> words
['This', 'is', 'a', 'very', 'long', 'string', 'that', 'I', 'would', 'like', 'to',
 'split', 'into', 'two', 'shorter', 'strings']
>>> k = len(words)//2   1
>>> ' '.join(words[:k])
'This is a very long string that I would'
>>> ' '.join(words[k:])
'like to split into two shorter strings'

CodePudding user response:

I would search outward from the center for a space, and return the halves as a tuple.

def splitter(longstring) -> (str,str):
   mid = len(longstring) // 2
   for i in range(mid):
      if longstring[mid   i] == ' ':
          # Note the ' 1' to elide the space from the second half.
          return longstring[:mid i], longstring[mid i 1:]
      elif longstring[mid - i] == ' ':
          return longstring[:mid-i], longstring[mid-i 1:]
   # In the edge case we return the entire string in the first element of the tuple.
   return longstring, ''

Some samples sample demonstrating the usage

samples= [
       "This is a very long string that I would like to split into two shorter strings",
       "This is a very long string that I wouldliketosplitinto two shorter strings",
       "This is a very long string thatIwouldliketo split into two shorter strings",
       "This isaverylongstringthatIwouldliketosplitintotwoshorterstrings",
       "ThisisaverylongstringthatIwouldliketosplitintotwoshorterstring s",
       "ThisisaverylongstringthatIwouldliketosplitintotwoshorterstrings"]

for long in samples:
   print(long)
   left, right = splitter(long)
   print(f"A: {left} ({len(left)} chars)")
   print(f"B: {right} ({len(right)} chars)")
   print("-----------")

This produces output like:

This is a very long string that I would like to split into two shorter strings
A: This is a very long string that I would (39 chars)
B: like to split into two shorter strings (38 chars)
-----------
This is a very long string that I wouldliketosplitinto two shorter strings
A: This is a very long string that I (33 chars)
B: wouldliketosplitinto two shorter strings (40 chars)
-----------
This is a very long string thatIwouldliketo split into two shorter strings
A: This is a very long string thatIwouldliketo (43 chars)
B: split into two shorter strings (30 chars)
-----------
This isaverylongstringthatIwouldliketosplitintotwoshorterstrings
A: This (4 chars)
B: isaverylongstringthatIwouldliketosplitintotwoshorterstrings (59 chars)
-----------
ThisisaverylongstringthatIwouldliketosplitintotwoshorterstring s
A: ThisisaverylongstringthatIwouldliketosplitintotwoshorterstring (62 chars)
B: s (1 chars)
-----------
ThisisaverylongstringthatIwouldliketosplitintotwoshorterstrings
A: ThisisaverylongstringthatIwouldliketosplitintotwoshorterstrings (63 chars)
B:  (0 chars)
-----------

CodePudding user response:

I suppose you cannot split it using based on space character closest to center, you can directly split it from centre using this

str_0 = "This is a very long string that I would like to split into two shorter strings"
str1 = str_0[0:len(str_0)//2]
str2 = str_0[len(str_0)//2:]
print(str1)
print(str2)
  • Related