x = [1,2,3] # x is a list, not @x
print x[2] # element 2 of list x, not $x[2]
x = { "foo": "bar" } # x is a dictionary, not %x
x = Foo() # x is an instance of class Foo, not $x
while x > 2:
if 'foo' in bar:
x -= 1
print "foo!"
x -= 1
scalar
|
int, float, str, etc. |
array
|
list
|
hash
|
dict
|
Because native types are objects, they all work with the same operators, so there's no == versus eq distinction. But this means that 1 != "1" because an int can't equal a str. Of course, str(1) == "1".
foreach my $item (@array) {
print $item."\n";
}
|
for item in array: print item |
but in python the same syntax works for dictionaries:
foreach my $key (keys %hash) {
print $key."\n";
} | for key in hash: print key |
and in fact for anything that can be iterated over, such as strings:
foreach my $character (split(//,$string) {
print $character."\n";
} | for character in string: print character |
Regexp syntax the same as perl, but used with OO syntax:
$x = "foo"; $x =~ s/oo/ee/g; | import re
x = "foo"
x = re.sub("oo","ee",x) |
$x = "foo";
@matches = ($x =~ /(o)/g);
if(scalar @matches) {
print $matches[0]."\n";
}
|
import re
x = "foo"
results = re.search("(o)",x)
if results is not None:
print results.group(1)
|
Pretty much everything's an object, including classes and native types:
>>> x = [1,2,3,2] >>> print x.count(2) 2 >>> x.append(4) >>> print x [1,2,3,2,4]
So your classes can subclass builtin types
class MyString(str):
def foo(self):
return "foo"
# MyStrings behave like strings but have a foo() method too
Many things you'd find in man perlfunc are methods on builtin types:
"FOO".lower() == "foo"
"a,b,c".split(",") == ["a","b","c"]
[1,2,3].sort() == None
(sorts in place, returns nothing!)
{"key":"value"}.keys() == ["key"]
file("foo.txt")
(looks like a builtin, but is actually a constructor for an object of type 'file')
In perl, if something should work, it mostly does:
> print 1 + "1" 2
Python distinguishes between types of scalars (numbers, strings, etc) more rigidly:
>>> print 1 + "1" TypeError: unsupported operand type(s) for +: 'int' and 'str'
Python has exceptions, so you can still write a block of code that might blow up without having to explicitly check for failures:
try: print 1 + "1" print "Well, that went fine" except TypeError: print "I can't add up strings and integers, sorry."
print adds a newline by defaultuse strict built in. But you can run pycheckermap, filter and sort as builtins. Now it has list comprehensions which let you write list-processing stuff like [(x.foo()+10)*(y.bar()+10) for x,y in item.items() if x != 'baz']
pyrex to mix C and python inline and then compile the results to C
class Foo():
def bar(self):
return "baz"
f = Foo
x = f() # x is now an instance of Foo