Remove white space without built-in function .strip() or others

hi guys, need help here.

I want to remove whitespace in a string without built-in function. I think about using a loop. Then I get stuck.
The logic is :

  1. loop the string
  2. if the string != ’ ':
  3. print string[i+1:]

This is the sample code:

string = ’ I love Aru ’

temp = ‘’
for i in range(len(string)):
if string[i] != ’ ':
temp = string[i+1:]

…it’s not finished

remove white spaces, how? All whitespaces so we get:


or remove all leading and trailing white spaces so we get:

'I love Aru'

Before we can solve a problem, we need clear requirements/understanding of the objective

Given we are going to mutate, I would go for a mutable data type (list) for the variable we use to store the result (temp variable)

1 Like

Thx for replying @stetim94. I meant trailing white spaces.
if i have a string,
str = 'I______Love___ Aru___ '.
The return i expected is:
new_str = ‘I Love Aru’

() is whitespace, because when I posted without () here, my post automatically convert to ‘I Love Aru’ :sweat_smile:

this then becomes a multi step process:

remove all the leading whitespaces
remove all the trailing whitespaces
reduce all spaces to one between words

sounds like regex is almost worth considering. Or does that also count as built-in function?

1 Like

I agree with @stetim94. I just got done with a Regex course and it is perfect for cleaning data and such. It is easy to learn too. Thanx for letting me comment

maybe the basic of regex, complex regular expressions are difficult to learn. And might sometimes not be desired (more difficult to maintain)

Thank you for answering my question. But I think regex is also a “short-path”. What I need is using the old way, just loop and condition, the logic, so it can be applied in any language.

Thanx for answering man. Appreciate it.
But, What i was asking is to use the old way, just loop and condition.

1 Like

which languages do not support regex then? Most mainstream programming languages support regex as far as I know

in fact, loop and conditional syntax will vary more between languages.

#A random string with lot of spaces at before in middle and after.

string = "        I               love      cheese           and grapes       "

#remove the extra spaces at the begining and the end of the string

while string[0] == " ":
    string = string[1:]
while string[-1] == " ":
    string = string[:-1]

#use a list to store the characters you want to keep from the original string

new_string = [] 
for i in range(len(string)):
    if string[i] == " " and string[i+1] ==" ":

#Use .join to concatenate the list data back to a string.

new_string = "".join(new_string)    

Still unsure to how much extend about the “no built-in functions”. like append(), join() or even replace()

while "  " in string:
    string = string.replace("  ", " ")