[Tutor] making a string
Martin A. Brown
martin at linux-ip.net
Sun May 26 05:31:49 CEST 2013
Greetings Tim,
: I'm new to this, just getting through the first Mark Lutz book.
Python objects, either variables your ham below or the string 'spam'
you entered manually have a specific type. Each and every variable
or object has a type.
I think you are trying to figure out how you started with a string
that looked like 'spam' (and Python calls a <type 'str'>) and end up
with something that looks like:
['s','p','a','m']
Well, I would encourage you to play with everything at the Python
prompt. You should be able to enter a tête-à-tête with Python as
follows. This is what I see when I type 'python' and get an
interactive console:
Python 2.7.2 (default, Aug 19 2011, 20:41:43) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Then, I can start playing with variables, strings, lists and all the
other things that Mark Lutz may mention.
Here's what I actually typed and what Python told me:
>>> spam = 'spam'
>>> type(spam)
<type 'str'>
>>> ham = list(spam)
>>> type(ham)
<type 'list'>
>>> viking = ''.join(ham)
>>> viking
'spam'
>>> type(viking)
<type 'str'>
So, the point I'm trying to make here is that you did quite a bit
in just one line, by calling:
>>> ham=list('spam');ham
Consider playing a bit with the interpreter.
: ham=list('spam');ham
: ['s','p','a','m']
:
: How do I get a string back?
I will now try to annotate my session above, so that you can maybe
see how I was able to get a string.
>>> spam = 'spam' # -- variable spam now contains string 'spam'
>>> type(spam)
<type 'str'> # -- and Python tells me it's a string
>>> ham = list(spam) # -- I'm running your command
>>> type(ham)
<type 'list'> # -- Wait, what!? It's a list?! Oh. Yeah.
>>> viking = ''.join(ham) # -- create a string of the list elements
>>> viking
'spam'
>>> type(viking) # -- ah, here's our string!
<type 'str'>
Try out the .join(ham) trick with other strings. For
example...what happens when you try these yourself:
>>> ham = list('spam')
>>> '-'.join(ham)
>>> ':'.join(ham)
>>> 'B'.join(ham)
>>> ' '.join(ham)
Hopefully, you see that there's no magic here at all--just that
you have learned how create a string with all of the elements in a
list. Try something else for your amusement, as well...
>>> ' '.join(list('frobnitz'))
Does that make sense? Welcome to Python, and Mark Lutz has been
writing books on Python for almost as long as Python has been
around. So, good luck and ask questions here. There's quite a
group here willing to help.
-Martin
--
Martin A. Brown
http://linux-ip.net/
More information about the Tutor
mailing list