Python - Using while loop to slice off the first character of a string

Introduction

The next example keeps slicing off the first character of a string until the string is empty.

An empty string is false.

It's typical to test an object directly like this instead of using the more verbose equivalent (while x != '':).

Demo

x = 'test' 
while x:                  # While x is not empty 
    print(x, end=' ')     # In 2.X use print x, 
    x = x[1:]             # Strip first character off x
# w  ww .  j a  v  a2s . c o m

Result

The end=' ' keyword argument used here to place all outputs on the same line separated by a space.

Related Topic