Thales Pereira Thales Pereira - 1 month ago 6
Python Question

Why for loop is splitting strings of user input?

Why looping over the user input results splits the values inserted?

text = ("Insert something: ")
inputs = raw_input(text).strip("\n")

for i in inputs:
print i


Results

Insert something: 01 02 03
0
1

0
2

0
3


expected result:

01
02
03

Answer

Strings are sequences, containing individual characters. You are iterating over the inputs string, so you get the individual characters.

If you wanted to iterate over a list of whitespace-separated words you should first split the string into a list:

for i in inputs.split():

The .strip('\n') call on the result of raw_input() is redundant for two reasons:

  • raw_input() returns the entered string without a newline, so there is no need to remove a newline character here.
  • the str.split() method, without arguments, splits on arbitrary-length whitespace (spaces, tabs, newlines, etc.) and removes whitespace at the start and end. So even if there was a newline to remove, str.split() would take care of this for you.