make a string a list

Matimus mccredie at gmail.com
Thu May 29 17:54:50 EDT 2008


On May 29, 2:30 pm, Nikhil <mnik... at gmail.com> wrote:
> or a string iterable ? How can I do that. I have lots of '\r\n'
> characters in the string which I think can be easier if it were made
> into a list and I can easily see if the required value (its a numeral)
> is present in it or not after some position or after some characters'
> position.
>
> Thanks,
> Nikhil

I a little confused by what you are trying to do, but:

Strings are iterable.

>>> for c in "hello":
...   print "look, a letter", c
...
look, a letter h
look, a letter e
look, a letter l
look, a letter l
look, a letter o

And indexable:

>>> "hello"[0]
'h'

And converting to a list is done like this:

>>> list("hello")
['h', 'e', 'l', 'l', 'o']

They also have some pretty nifty methods:

>>> "hello\r\nworld\r\nlets\r\nsplit\r\n".split("\r\n")
['hello', 'world', 'lets', 'split', '']

>>> "hello world".index('world')
6

>>> "hello world".index('l')
2
>>> "hello world".index('l', 2+1)
3
>>> "hello world".index('l', 3+1)
9
>>> "hello world".index('l', 9+1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

Hopefully some of that helps.

Matt



More information about the Python-list mailing list