Luchian Grigore
Luchian Grigore

Reputation: 258618

Iterating through python string array gives unexpected output

I was debugging some python code and as any begginer, I'm using print statements. I narrowed down the problem to:

paths = ("../somepath") #is this not how you declare an array/list?
for path in paths:
    print path

I was expecting the whole string to be printed out, but only . is. Since I planned on expanding it anyway to cover more paths, it appears that

paths = ("../somepath", "../someotherpath")

fixes the problem and correctly prints out both strings.

I'm assuming the initial version treats the string as an array of characters (or maybe that's just the C++ in me talking) and just prints out characters.?...??

I'd still like to know why this happens.

Upvotes: 2

Views: 81

Answers (3)

Gabriel
Gabriel

Reputation: 3594

Tested it and the output is one character per line

So all is printed one character per character

To get what you want you need

# your code goes here
paths = ['../somepath'] #is this not how you declare an array/list?
for path in paths:
    print path

Upvotes: 0

vks
vks

Reputation: 67968

paths = ["../somepath","abc"]

This way you can create list.Now your code will work .

paths = ("../somepath", "../someotherpath") this worked as it formed a tuple.Which again is a type of non mutable list.

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239473

("../somepath")

is nothing but a string covered in parenthesis. So, it is the same as "../somepath". Since Python's for loop can iterate through any iterable and a string happens to be an iterable, it prints one character at a time.

To create a tuple with one element, use comma at the end

("../somepath",)

If you want to create a list, you need to use square brackets, like this

["../somepath"]

Upvotes: 5

Related Questions