Showing posts with label strings. Show all posts
Showing posts with label strings. Show all posts

Saturday, January 21, 2012

Playing with Print

print prints things. Well, duh. Let's see how....

>>>print 'hello'
hello


OK, single quotes work.

>>>print "Hello"
Hello


And double quotes. What about printing quotes? I bet I can nest one type of quote inside the others...

>>>print "Python's Print Puts Pennies in Paragraphs"
Python's Print Puts Pennies in Paragraphs


>>>print 'The Python Quoth "Bring out your dead!"'
The Python Quoth "Bring out your dead!"


What about printing both sorts together?

Hmmm...

Maybe I could concatenate...

>>>print 'The Python Quoth "' + "You're no fun anymore!" + '"'
The Python Quoth "You're no fun anymore!"


That worked. But Python's tricky. Maybe there's an easier way. Multiple quotes?

>>> print ""The Python Quoth "I'm a lumberjack and I'm OK!"""
File "", line 1
print ""The Python Quoth "I'm a lumberjack and I'm OK!"""
^
SyntaxError: invalid syntax


>>> print ''The Python Quoth "I'm a lumberjack and I'm OK!"''
File "", line 1
print ''The Python Quoth "I'm a lumberjack and I'm OK!"''
^
SyntaxError: invalid syntax


>>> print '''The Python Quoth "I'm a lumberjack and I'm OK!"''''
File "", line 1
print '''The Python Quoth "I'm a lumberjack and I'm OK!"''''
^
SyntaxError: EOL while scanning string literal


>>> print """'The Python Quoth "I'm a lumberjack and I'm OK!""""
File "", line 1
print """'The Python Quoth "I'm a lumberjack and I'm OK!""""
^
SyntaxError: EOL while scanning string literal


>>> print """'The Python Quoth "I'm a lumberjack and I'm OK!"""
'The Python Quoth "I'm a lumberjack and I'm OK!


Dang, lost the final double quotes. Lessee...

>>> print """'The Python Quoth "I'm a lumberjack and I'm OK!\""""
'The Python Quoth "I'm a lumberjack and I'm OK!"


Aha! Escaping quotes works!

>>>print 'I\'m a lumberjack and I\'m OK!'
I'm a lumberjack and I'm OK!


Let's try mixing some numbers in.

>>> print 'There are ' + 3 + 'Pythons upon the desk.'
Traceback (most recent call last):
File "", line 1, in
TypeError: cannot concatenate 'str' and 'int' objects


>>> print 'There are ', 3, ' Pythons upon the desk.'
There are 3 Pythons upon the desk.


Commas work, but too many spaces are in there.

>>> print 'There are',3,'Pythons upon the',3,'rd desk.'
There are 3 Pythons upon the 3 rd desk.


OK, the first number is spaced right, how do we get the other one without spaces?

>>> print 'There are',3,'Pythons upon the '+ str(3) +'rd desk.'
There are 3 Pythons upon the 3rd desk.


OK, so we can concatenate with '+', but only if it's a string.

We can use numerals if we put it together with a comma, but then we get an added space.

We can make a numeral into a string with str() and then we can concatenate with + so that we don't get added spaces.

I think I get it.

I'm sure there are a dozen other ways to do this, and at least ten of them may be better. But that'll do for now.