Hey, everyone. I know how to strip certain characters from a string using for loop. Can you give an example of how that can be done with the use of while loop?

I am trying to figure out a situation which requires looping...

>>> string
'Take out all the 111111111111111111'
>>> string.replace('1','').strip()
'Take out all the'

See what i mean?

If you just need a while example...

>>> x = 0
>>> while x < 10:
	x += 1

	
>>> x
10

Hey, everyone. I know how to strip certain characters from a string using for loop. Can you give an example of how that can be done with the use of while loop?

Please post your code with the for loop and we'll rewrite it with a while loop :)

Please post your code with the for loop and we'll rewrite it with a while loop :)

Here is the code:

phrase = "Goodbye, cruel, sad, world!"
stripped_phrase = ""
    for c in phrase.lower():
        if c in "'!,.? 1234567890":
            c = ""
        stripped_phrase += c

Using a for loop:

>>> phrase = "Goodbye, cruel, sad, world!"
>>> for x in "'!,.? 1234567890":
	if x in phrase:
		phrase = phrase.replace(x,'')

		
>>> phrase
'Goodbyecruelsadworld'

I don't think you can use a while loop in this instance without using a for loop with it...

For is a way you can use while, but in this instance it nearly functions just like if:

for x in "'!,.? 1234567890":
	while x in phrase:
		phrase = phrase.replace(x,'')
>>> phrase
'Goodbyecruelsadworld'

here is something closer to your original code... (if that is what your required to do.)

>>> def clean(phrase):
	output = ''
	for x in phrase:
		if x in "'!,.? 1234567890":
			continue
		output += x
	return output

>>> clean("Goodbye, cruel, sad, world!")
'Goodbyecruelsadworld'

while:

>>> def clean(phrase):
	output = ''
	for x in phrase:
		while x in "'!,.? 1234567890":
			break
		else:
			output += x
	return output

>>> clean("Goodbye, cruel, sad, world!")
'Goodbyecruelsadworld'

another way to use while:

>>> def clean(phrase):
	output = ''
	for x in phrase:
		while x in "'!,.? 1234567890" and x != '':
			x = ''
		output += x
	return output

>>> clean("Goodbye, cruel, sad, world!")
'Goodbyecruelsadworld'

You can always replace a for loop by a while loop:

for item in sequence:
  do_something()

is replaced by

sequence = list(sequence) # <--unnecessary if sequence is a string, tuple or list
i = 0
while i < len(sequence):
  item = sequence[i]
  do_something()
  i += 1

but nobody needs to do that :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.