473,396 Members | 2,013 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

how do i change from string to list

I have the following

s = "spot"

which I would like to change to a list

l = ['s','p','o','t']

I have tried l = eval(s) but I get the error

File "<string>", line 1, in ?
NameError: spot

thank you all for your time
Jul 18 '05 #1
14 1987
str='spot'

lst = [] # declare the list first
for letter in str:
lst.append(letter) # append to the list

print lst

result: ['s', 'p', 'o', 't']

cheerz,
Ivo.
"john" <mi******@hotmail.com> wrote in message
news:99**************************@posting.google.c om...
I have the following

s = "spot"

which I would like to change to a list

l = ['s','p','o','t']

I have tried l = eval(s) but I get the error

File "<string>", line 1, in ?
NameError: spot

thank you all for your time

Jul 18 '05 #2
On 24 Oct 2004 11:05:28 -0700, john <mi******@hotmail.com> wrote:
I have the following

s = "spot"

which I would like to change to a list

list('spot')

['s', 'p', 'o', 't']

/Jorgen

--
// Jorgen Grahn <jgrahn@ Ph'nglui mglw'nafh Cthulhu
\X/ algonet.se> R'lyeh wgah'nagl fhtagn!
Jul 18 '05 #3
Ivo Woltring wrote:
str='spot'

lst = [] # declare the list first
for letter in str:
lst.append(letter) # append to the list

print lst
I just would have used list("spot").
result: ['s', 'p', 'o', 't']


Same result but faster, more transparent, and with a lot less code.

Also, please don't top-post.
--
Michael Hoffman
Jul 18 '05 #4
Michael Hoffman wrote:
Ivo Woltring wrote:
str='spot'

lst = [] # declare the list first
for letter in str:
lst.append(letter) # append to the list

print lst

I just would have used list("spot").
result: ['s', 'p', 'o', 't']

Same result but faster, more transparent, and with a lot less code.

Also, please don't top-post.


Also, if for some reason you didn't want to use list that would look
more elegant as a list comprehension:
y = "Hello!"
[x for x in y] ['H', 'e', 'l', 'l', 'o', '!']


Jul 18 '05 #5

I agree completely!
Didn't know the list() though.
But all work so my answer is just as valid as yours

;-))
Ivo

"Ivo Woltring" <Th********@ivonet.nl> wrote in message
news:41*********************@reader20.nntp.hccnet. nl...
str='spot'

lst = [] # declare the list first
for letter in str:
lst.append(letter) # append to the list

print lst

result: ['s', 'p', 'o', 't']

cheerz,
Ivo.
"john" <mi******@hotmail.com> wrote in message
news:99**************************@posting.google.c om...
I have the following

s = "spot"

which I would like to change to a list

l = ['s','p','o','t']

I have tried l = eval(s) but I get the error

File "<string>", line 1, in ?
NameError: spot

thank you all for your time


Jul 18 '05 #6
"Ivo Woltring" <Th********@ivonet.nl> wrote in message news:<41*********************@reader1.nntp.hccnet. nl>...
I agree completely!
Didn't know the list() though.
But all work so my answer is just as valid as yours

;-))
Ivo


This will probably work, too -- is it "valid"?

s = 'spot'
slen = len(s)
alist = [''] * slen
for i in range(slen):
alist[i] = s[i]

You can write code in Perl or Intercal [bonus points if you can tell
the difference] and it's "valid" in the sense that it works, but there
are many more considerations than that.
Jul 18 '05 #7
How do you do the opposite? List to string? Shortest method I've found is:
''.join(["H", "e", "l", "l", "o"])


--
mvh Björn
Jul 18 '05 #8
BJörn Lindqvist wrote:
How do you do the opposite? List to string? Shortest method I've found is:
''.join(["H", "e", "l", "l", "o"])


That is the obvious way to do it.
--
Michael Hoffman
Jul 18 '05 #9
Michael Hoffman wrote:
BJörn Lindqvist wrote:
How do you do the opposite? List to string? Shortest method I've found
is:
>''.join(["H", "e", "l", "l", "o"])
That is the obvious way to do it.


We have different notions of obviousness, obviously:
str(['H', 'e', 'l', 'l', 'o'])

"['H', 'e', 'l', 'l', 'o']"

:-)

Peter

Jul 18 '05 #10
Hi John,
Although you already have the reply to your question, I thought I
should point one thing out. I have seen plenty of newbies wanting to
convert a string to a list so that they can do some sort of list
related manipulation on it. The good thing about python strings though
is, they are valid "sequences", which means that any sequence related
operations can also be carried out on strings.

For example:
s = "foobar"
for i in s: .... print i,
....
f o o b a r s[3:] 'bar' s[:-1] 'fooba'


....but I guess you already knew that :)

HTH someone,
Regards
Steve
Jul 18 '05 #11
Michael Hoffman wrote:
> ''.join(["H", "e", "l", "l", "o"])
That is the obvious way to do it.


As compared to the less obvious ways of

import array
array.array("c", list("this is a test")).tostring() 'this is a test' import cStringIO
f = cStringIO.StringIO()
for c in list("this is a test"): .... f.write(c)
.... print f.getvalue() this is a test import operator
reduce(operator.add, list("this is a test")) 'this is a test' def join(fields): .... N = len(fields)
.... if N == 1: return fields[0]
.... if N == 2: return fields[0] + fields[1]
.... N = N//2
.... return join([join(fields[:N]), join(fields[N:])])
.... join(list("this is a test")) 'this is a test'

# only works for single character elements in the list
# (or larger strings that don't have ", ") s = "\"Let's go to the zoo!\", said \\Alice/\n"
print s "Let's go to the zoo!", said \Alice/
list(s) ['"', 'L', 'e', 't', "'", 's', ' ', 'g', 'o', ' ', 't', 'o', ' ', 't',
'h', 'e', ' ', 'z', 'o', 'o', '!', '"', ',', ' ', 's', 'a', 'i', 'd', '
', '\\', 'A', 'l', 'i', 'c', 'e', '/', '\n'] print eval(repr(list(s))[1:-1].replace(", ", " ")) "Let's go to the zoo!", said \Alice/


:)

Andrew
da***@dalkescientific.com
Jul 18 '05 #12
Peter Otten wrote:
We have different notions of obviousness, obviously:
str(['H', 'e', 'l', 'l', 'o'])


"['H', 'e', 'l', 'l', 'o']"

:-)


That's a joke, right? :-)
--
Michael Hoffman
Jul 18 '05 #13
Andrew Dalke <ad****@mindspring.com> wrote:
...
>>> import cStringIO
>>> f = cStringIO.StringIO()
>>> for c in list("this is a test"):

... f.write(c)


f.writelines(list('this is a test'))

would appear to me a more natural approach than the loop. Yeah, the
method's name sucks -- it doesn't just write *lines*, etc. I guess it
originally came from some sort of parallel with 'readlines'.
Alex
Jul 18 '05 #14
agreed
But I wasn't aware of the list() function and than my version wasn't so bad

but I agree about the more considerations though

Ivo

"John Machin" <sj******@lexicon.net> wrote in message
news:c7**************************@posting.google.c om...
"Ivo Woltring" <Th********@ivonet.nl> wrote in message

news:<41*********************@reader1.nntp.hccnet. nl>...
I agree completely!
Didn't know the list() though.
But all work so my answer is just as valid as yours

;-))
Ivo


This will probably work, too -- is it "valid"?

s = 'spot'
slen = len(s)
alist = [''] * slen
for i in range(slen):
alist[i] = s[i]

You can write code in Perl or Intercal [bonus points if you can tell
the difference] and it's "valid" in the sense that it works, but there
are many more considerations than that.

Jul 18 '05 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Bj?rn | last post by:
HY, my problem is the following: I want to give a very big application the ability, to change the language at runtime. It's written in Visual C++ 6.0. All language depending strings and so...
4
by: Richard Cornford | last post by:
For the last couple of months I have been trying to get the next round of updates to the FAQ underway and been being thwarted by a heavy workload (the project I am working on has to be finished an...
2
by: Isz | last post by:
Hi Group: I would like to know if it is possible to change the name of an attribute to something else. My setup is like this: I have serveral SQL tables that I nest and join so that it all...
2
by: Daniel Lidström | last post by:
Hi, I would like to know the cleanest way to change the serialization of my Line class from: <Line staStart="2327.02" length="10.00000003390744"> <End>549016.570965 57945.741122</End>...
4
by: N. Graves | last post by:
Hello... thank you for your time. I have a form that has a List box of equipotent records and a sub form that will show the data of the equipment select from the list box. Is it possible to...
2
by: Greg Strong | last post by:
Hello All, Is it possible to change table field lookup properties in code? I've been able to change other field properties in code, however so far no luck with field lookup properties. What...
18
by: Daniel | last post by:
Hey guys I have an instance of an object say: List<Object> myList = new List<Object>(); Object myObject = new Object(); myObject.PositionVector = new Vector3(10,10,10); ...
37
by: sam44 | last post by:
Hi, At startup the user log on and chooses the name of a client from a dropdownlist, which then changes dynamically the connection string (the name of the client indicates which database to use)....
5
by: Gary | last post by:
I am using List<MyClassto store a bunch of MyClasses. And in my program, I want to change the content of one class in this list. However, it seems to me that this list keeps an original copy and is...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.