I am out of trial and error again Lists

Denis McMahon denismfmcmahon at gmail.com
Fri Oct 24 19:21:43 EDT 2014


On Fri, 24 Oct 2014 16:58:00 -0400, Seymore4Head wrote:

> I make lots of typing mistakes.  It is not that. Did you see the short
> example I posted?
> 
> name="123-xyz-abc"
> for x in name:
>     if x in range(10):
>         print ("Range",(x))
>     if x in str(range(10)):
>         print ("String range",(x))
> 
> It doesn't throw an error but it doesn't print what you would expect.

It prints exactly what I expect.

Try the following:

print(str(range(10)), type(str(range(10))))
print(str(list(range(10))), type(str(listr(range(10)))))

In python 3, str(x) just wraps x up and puts it in a string. range(x) 
generates an iterable range object.

hence str(range(10)) is a string telling you that range(10) is an iterable 
range object with certain boundaries.

However, list(iterable) expands the iterable to the full list of possible 
values, so str(list(range(10))) is a string representation of the list 
containing the values that the iterable range(10) creates.

Note that whether you're looking at a string representation of a value or 
the value itself is a lot clearer in the interpreter console where 
strings are displayed with quotes.

-- 
Denis McMahon, denismfmcmahon at gmail.com



More information about the Python-list mailing list