joke = "It's hard to explain puns to kleptomaniacs"
punchline = 'because they always take things literally.'
poem = """
The Ogre does what ogres can,
Deeds quite impossible for Man,
But one prize is beyond his reach:
The Ogre cannot master Speech.
About a subjugated plain,
Among its desperate and slain,
The Ogre stalks with hands on hips,
While drivel gushes from his lips.
"""
Raw strings
print "first line\nsecond line"
print r"first line\nsecond line"
- Unicode and byte strings…
"Spam " + "eggs"
"Spam " * 10
Converting objects to strings
str(42) == "42"
and strings to objects
int("42") == 42
Iteration
for char in "pymntos":
print char
Slicing
book_description = "A cautionary tale of the decadent downside of the American dream."
book_description[2:12]
book_description = "A cautionary tale of the decadent downside of the American dream."
book_description[2:12] = "silly"
- Python strings are immutable for performance and safety.
- The
str
methods and functions return a newstr
object.
book_description = "A cautionary tale of the decadent downside of the American dream."
print book_description.replace("cautionary", "silly")
print book_description
The original string is unchanged.
incoherent = "Has Anyone Really Been Far Even as Decided to Use Even Go Want to do Look More Like?"
print incoherent.upper()
print incoherent.title()
print incoherent.swapcase()
print incoherent
", ".join(["one", "two", "three"])
"one,two,three".split(",")
laws = """ First Law of Thermodynamics: You can't win.
Second Law of Thermodynamics: You can't break even.
Third Law of Thermodynamics: You can't stop playing."""
for law in laws.splitlines():
print law.split(":")[1]
book_description = "A cautionary tale of the decadent downside of the American dream."
(
"of" in book_description,
book_description.startswith("A"),
book_description.endswith("dream."),
book_description.find("tale"),
book_description.find("Python")
)
book_text = """
In my younger and more vulnerable years my father gave me some advice
that I've been turning over in my mind ever since. "Whenever you feel
like criticizing any one", he told me, "just remember that all the
people in this world haven't had the advantages that you've had."
""" # The first two sentences from The Great Gatsby.
book_text.count("my")
fish->registerLibrary(NEWC(BaseLibrary(r,iArrayGet ,"array.create" ,-1,true ,"array","int,..." )));
fish->registerLibrary(NEWC(BaseLibrary(r,iArrayLose ,"array.delete" , 1,true ,"void" ,"array" )));
fish->registerLibrary(NEWC(BaseLibrary(r,iArrayDim ,"array.dim" , 1,true ,"int" ,"array" )));
fish->registerLibrary(NEWC(BaseLibrary(r,iArraySize ,"array.size" , 2,true ,"int" ,"array,int")));
fish->registerLibrary(NEWC(BaseLibrary(r,iArrayConvert,"array.convert", 1,true ,"array","mat/tens")));
fish->registerLibrary(NEWC(BaseLibrary(r,iArrayCopy ,"array.copy" , 1,false,"array","array")));
fish->registerLibrary(NEWC(BaseLibrary(r,iArrayCommand,"array.command", 1,true ,"bool" ,"array")));
my_code.cpp
import re
pattern = re.compile(r'.*registerLibrary[^"]*"([^"]*)".*')
results = []
for line in open("my_code.cpp").readlines():
match = pattern.match(line)
if match:
results.append(match.groups()[0])
print results
String interpolation with %
"%s and %s" % ("Spam", "eggs")
The string format
method
"{} and {}".format("Spam", "eggs")
The format
method is new (Python 2.6+) and generally preferred. It
is extensible.
template = "Hello {0}, welcome to {1}. {0} is {2}."
template.format("David", "Minnesota", "Tall")
template = "Hello {name}, welcome to {place}. {name} is {description}."
template.format(name="David", place="Minnesota", description="Tall")
class Purchase:
pass
transaction = Purchase()
transaction.number = 3
transaction.customer = "Bill"
transaction.product = "Widget"
receipt = "Thank you {0.customer} for your purchase of {0.number} {0.product}s."
print receipt.format(transaction)
- Access object attributes
- dictionary keys
- list indexing
number = 123
"decimal: {0}, hex: {0:X}, binary: {0:b}".format(number)
from math import pi, e
for i in [-2,-1,0,1,2]:
scale = 10**i
print "{:9.4f} {:9.4f} {:9.4f}".format(10 * scale, pi * scale, e * scale)
words = "Has Anyone Really Been Far Even as Decided to Use Even Go Want to do Look More Like?".split()
for i in range(6):
print ("{:10}" * 3).format(words.pop(0), words.pop(0), words.pop(0))
Templating libraries
<title>{% block title %}{% endblock %}</title>
<ul>
{% for user in users %}
<li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>
- Jinja2 http://jinja.pocoo.org/docs/
Python port of the Common Lisp FORMAT function.
from clformat import clformat
import time
clformat("There is a ~a in my string.", "foo")
clformat("~r cat~:p", 10)
clformat("~{~a~^-~}", range(8))
clformat("The year is ~@r", time.localtime().tm_year)
clformat("~#[ none~; ~A~; ~A and ~A~:;~@{~#[~; and~] ~A~^,~}~].",
"James", "Simon", "Jason", "Kerry")
- Not for the faint of heart…
- https://github.com/jkfurtney/clformat
- Python port of FORTRAN’s format statement: https://pypi.python.org/pypi/fortranformat
Produce the number 2014 without any numbers in your source code
sum(ord(c) for c in 'Happy new year to you!')
- see also
chr()
(orunichr()
) which is the inverse oford()
.
- 110,000 characters and symbols are defined for about 100 written scripts.
- Python 2:
str
objects represent 8-bit text and binary dataUnicode
object
- Python 3:
str
object for Unicode text and 8-bit textbytes
type for binary data
- Python 2.6+ and 3 have a
bytearray
type (mutable version of bytes) - Practical Unicode: How do I stop the pain: http://nedbatchelder.com/text/unipain.html
- http://www.joelonsoftware.com/articles/Unicode.html
- more stuff in the
string
module json
&xml
modulesStringIO
module use strings asfile
objectsstruct
module for binary IO
"""
Thank You!
"""