4

What are other ways to split a string without using the split() method? For example, how could ['This is a Sentence'] be split into ['This', 'is', 'a', 'Sentence'] without the use of the split() method?

1
  • 1
    you can't split a list using split() Commented Oct 1, 2015 at 0:12

10 Answers 10

13
sentence = 'This is a sentence'
split_value = []
tmp = ''
for c in sentence:
    if c == ' ':
        split_value.append(tmp)
        tmp = ''
    else:
        tmp += c
if tmp:
    split_value.append(tmp)
Sign up to request clarification or add additional context in comments.

1 Comment

I appreciate the help but when I ran the code, it ['This', 'is', 'a'] but for some reason it cuts off 'Sentence'. Any reason why? I've ran each code line by line but I can't figure out what the issue is.
3

You can use regular expressions if you want:

>>> import re
>>> s = 'This is a Sentence'
>>> re.findall(r'\S+', s)
['This', 'is', 'a', 'Sentence']

The \S represents any character that isn't whitespace, and the + says to find one or more of those characters in a row. re.findall will create a list of all strings that match that pattern.

But, really, s.split() is the best way to do it.

Comments

2

A recursive version, breaking out the steps in detail:

def my_split(s, sep=' '):
    s = s.lstrip(sep)
    if sep in s:
        pos = s.index(sep)
        found = s[:pos]
        remainder = my_split(s[pos+1:])
        remainder.insert(0, found)
        return remainder
    else:
        return [s]

print my_split("This is a sentence")

Or, the short, one-line form:

def my_split(s, sep=' '):
    return [s[:s.index(sep)]] + my_split(s[s.index(sep)+1:]) if sep in s else [s]

Comments

1

Starting with a list of strings, if you would like to split these strings there are a couple ways to do so depending on what your desired output is.

Case 1: One list of strings (old_list) split into one new list of strings (new_list).

For example ['This is a Sentence', 'Also a sentence'] -> ['This', 'is', 'a', 'Sentence', 'Also', 'a', 'sentence'].

Steps:

  1. Loop through the strings. for sentence in old_list:
  2. Create a new string to keep track of the current word (word).
  3. Loop through the characters in each of these strings. for ch in sentence:
  4. If you come across the character(s) you want to split on (spaces in this example), check that word is not empty and add it to the new list, otherwise add the character to word.
  5. Make sure to add word to the list after looping through all the characters.

The final code:

new_list = []
for sentence in old_list:
    word = ''
    for ch in sentence:
        if ch == ' ' and word != '':
            new_list.append(word)
            word = ''
        else:
            word += ch
    if word != '':
        new_list.append(word)

This is equivalent to

new_list = []
for sentence in old_list:
    new_list.extend(sentence.split(' '))

or even simpler

new_list =  ' '.join(old_list).split(' ')

Case 2: One list of strings (old_list) split into a new list of lists of strings (new_list).

For example ['This is a Sentence', 'Also a sentence'] -> [['This', 'is', 'a', 'Sentence'], ['Also', 'a', 'sentence']].

Steps:

  1. Loop through the strings. for sentence in old_list:
  2. Create a new string to keep track of the current word (word) and a new list to keep track of the words in this string (sentence_list).
  3. Loop through the characters in each of these strings. for ch in sentence:
  4. If you come across the character(s) you want to split on (spaces in this example), check that word is not empty and add it to sentence_list, otherwise add the character to word.
  5. Make sure to add word to sentence_list after looping through all the characters.
  6. Append (not extend) sentence_list to the new list and move onto the next string.

The final code:

new_list = []
for sentence in old_list:
    sentence_list = []
    word = ''
    for ch in sentence:
        if ch == ' ' and word != '':
            sentence_list.append(word)
            word = ''
        else:
            word += ch
    if word != '':
        sentence_list.append(word)
    new_list.append(sentence_list)

This is equivalent to

new_list = []
for sentence in old_list:
    new_list.append(sentence.split(' '))

or using list comprehensions

new_list =  [sentence.split(' ') for sentence in old_list]

1 Comment

Please consider editing your post to add more explanation about what your code does and why it will solve the problem. An answer that mostly just contains code (even if it's working) usually wont help the OP to understand their problem.
1

This is simple code to split a char value from a string value; i.e

INPUT : UDDDUDUDU

s = [str(i) for i in input().strip()]
print(s)

OUTPUT: ['U','D','D','D','U','D','U','D','U']

1 Comment

You know, they didn't want to use strip(). Just a reminder.
1
sentence = 'This is a sentence'
word=""
for w in sentence :
    if w.isalpha():
        word=word+w

    elif not w.isalpha():
      print(word)
      word=""
print(word)

Comments

1
string1 = 'bella ciao amigos'
split_list = []
tmp = ''
for s in string1:
   if s == ' ':
       split_list.append(tmp)
       tmp = ''
   else:
       tmp += s
if tmp:
   split_list.append(tmp)

print(split_list)

Output: ------> ['bella', 'ciao', 'amigos']

reverse_list = split_list[::-1]
print(reverse_list)

Output: ------> ['amigos', 'ciao', 'bella']

Comments

1
def mysplit(strng):
    strng = strng.lstrip() 
    strng = strng.rstrip()
    lst=[]
    temp=''
    for i in strng:
        if i == ' ':
            lst.append(temp)
            temp = ''
        else:
            temp += i
    if temp:
        lst.append(temp)
    return lst
     
print(mysplit("Hello World"))
print(mysplit("   "))
print(mysplit(" abc "))
print(mysplit(""))

Comments

0

This is one of the most accurate replicas of split method:

def splitter(x, y = ' '):
    l = []
    for i in range(x.count(y) + 1):
        a = ''
        for i in x:
            if i == y: break
            a += i
        x = x[len(a) + 1 : len(x)]
        l.append(a)
    return ([i for i in l if i != ''])

Comments

-1
my_str='This is a sentence'
split_value = []
tmp = ''
for i in my_str+' ':
    if i == ' ':
        split_value.append(tmp)
        tmp = ''
    else:
        tmp += i   
print(split_value)

Just a small modification to the code already given

3 Comments

Care to explain why your code is better than the already accepted 5+ years old answer? Do you think that chaning the name of c to i really brings any value?
I don't know if my code is better or not, i just thought removing an additional if condition shortens the code a little that's all.
if you edit the answer to also explain why it removes the need of the last if statement (with the addition of the space at the end), then it would actually be a proper answer, and will receive + instead of -.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.