# Basic usage
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
# Using index of the passed object
print('Low limit: {0}, high limit: {1}'.format(10, 200))
# using the name of the argument.
print('Low limit: {low:.2f}, high limit: {high:.2f}'.format(low=10.0, high=200.3256))
# String format using dictionary
data = {'low': low, 'high': high}
print('Low limit: {low}, high limit: {high}'.format(**data))
- for item in array
- "else" clause for loops
count=0
while(count<5):
print count
count +=1
else:
print "count value reached %d" %(count)
class MyClass:
variable = "blah"
def function(self):
print "This is a message inside the class."
# create an object
myobjectx = MyClass()
# access to a variable
print myobjectx.variable
phonebook = {
"John" : 938477566,
"Jack" : 938377264,
"Jill" : 947662781
}
for name, number in phonebook.items():
print "Phone number of %s is %d" % (name, number)
# Removing a value
del phonebook["John"]
There is no switch-case in Python, so we can use dictionaries as switch-case alternative.
{
"Charlotte": 183,
"Tampa": 220,
"Pittsburgh": 222,
"Los Angeles": 475,
}.get(city, 300) # Default value is 300
- Return an iterable set of items
- Once the generator's function code reaches a "yield" statement, the generator yields its execution back to the for loop, returning a new value from the set
for word in words:
if word != "the":
word_lengths.append(len(word))
###############
word_lengths = [len(word) for word in words if word != "the"]
- *therest receive a variable number of arguments
- **options send functions arguments by keyword
def bar(first, second, third, **options):
if options.get("action") == "sum":
#do something
if options.get("number") == "first":
#do something
bar(1, 2, 3, action = "sum", number = "first")
pattern = re.compile(r"your pattern here")
#return search object or None
re.search(pattern, "I'm KT")
re.match(pattern, email)
Sets are lists with no duplicate entries.
print set("my name is Eric and Eric is my name".split())
Result:
set(['and', 'is', 'my', 'name', 'Eric'])
a.intersection(b)
find out which items in both lista.symmetric_difference(b)
find out which items in only one lista.difference(b)
find out which items only ina
and not inb
a.union(b)
merge 2 sets without duplications.
json
and cPickle
are the popular libs for serialize data in Python
- To serialize:
a.dumps([list])
- To unserialize:
a.loads([list])