Python String functions


Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes.


var1 = ‘Hello World!’

Built-in String Methods:

Methods: Description
capitalize(): Capitalizes first letter of string
center(width,fillchar): Returns a space-padded string with the original string centered to a total of width columns
count(str,beg=0,end=len(string)): Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given
find(str, beg=0 end=len(string)) Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise
rfind(str,beg=0,end=len(string)) Same as find(), but search backwards in string
index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str not found.
rindex(str,beg=0,end=len(string)) Same as index(), but search backwards in string
isalnum() Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise
isalpha() Returns true if string has at least 1 character and all characters are alphabetic and false otherwise
isdigit() Returns true if string contains only digits and false otherwise
islower() Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise
isnumeric() Returns true if a unicode string contains only numeric characters and false otherwise
isspace() Returns true if string contains only whitespace characters and false otherwise
istitle() Returns true if string is properly “titlecased” and false otherwise
isupper() Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise
len(string) Returns the length of the string
lower() Converts all uppercase letters in string to lowercase
upper() Converts lowercase letters in string to uppercase
lstrip() Removes all leading whitespace in string
max(str) Returns the max alphabetical character from the string str
min(str) Returns the min alphabetical character from the string str
replace(old,new[,max]) Replaces all occurrences of old in string with new or at most max occurrences if max given
rstrip() Removes all trailing whitespace of string
split(str=”“,num=string.count(str)) Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given
isdecimal() Returns true if a unicode string contains only decimal characters and false otherwise

SQLite in Android

Sqlite Data Types

DataType: Description
NULL: The value is a NULL value.
INTEGER: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
REAL: The value is a floating point value, stored as an 8-byte IEEE floating point number.
TEXT: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE)
BLOB: The value is a blob of data, stored exactly as it was input.

Create table query

The SQLite CREATE TABLE statement is used to create a new table in any of the given database. Creating a basic table involves naming the table and defining its columns and each column’s data type.


CREATE TABLE table_name( column1 datatype , column2 datatype, column3 datatype, ….. columnN datatype, );


CREATE TABLE employee( id integer primary key autoincrement, name text, job text, age integer, salary decimal);

Insert query

The SQLite INSERT INTO Statement is used to add new rows of data into a table in the database.


INSERT INTO TABLE_NAME (column1, column2, column3,…columnN) VALUES (value1, value2, value3,…valueN);


INSERT INTO employee(name, job, age, salary) values(“Steve”, “Clerk”, 27, 15000);

Select query

SQLite SELECT statement is used to fetch the data from a SQLite database table which returns data in the form of result table. These result tables are also called result-sets.


SELECT column1, column2, columnN FROM table_name;


SELECT name, job, age, salary FROM employee;

Delete query

The SQLite DELETE Query is used to delete the existing records from a table. You can use WHERE clause with DELETE query to delete selected rows, otherwise all the records would be deleted.


DELETE FROM table_name WHERE [condition];


DELETE FROM employee WHERE ID = 1;

What is new in Python 3.4


Python 2.7: print “hello world”

Python 3.0: print(“hello world”)

Integers: long renamed to int

Python 2.7: long stars

Python 3.0: int stars

Views And Iterators Instead Of Lists

dict methods dict.keys(), dict.items() and dict.values() return “views” instead of lists. For example, this no longer works: k = d.keys(); k.sort(). Use k = sorted(d) instead (this works in Python 2.5 too and is just as efficient).

Also, the dict.iterkeys(), dict.iteritems() and dict.itervalues() methods are no longer supported.

map() and filter() return iterators. If you really need a list, a quick fix is e.g. list(map(…)), but a better fix is often to use a list comprehension, or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop.

range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.

zip() now returns an iterator.

Ordering Comparisons

The ordering comparison operators (<, <=, >=, >) raise a TypeError exception when the operands don’t have a meaningful natural ordering. Thus, expressions like 1 < ‘’, 0 > None or len <= len are no longer valid, and e.g. None < None raises TypeError instead of returning False. A corollary is that sorting a heterogeneous list no longer makes sense – all the elements must be comparable to each other. Note that this does not apply to the == and != operators: objects of different incomparable types always compare unequal to each other.

builtin.sorted() and list.sort() no longer accept the cmp argument providing a comparison function. Use the key argument instead. N.B. the key and reverse arguments are now “keyword-only”.

The cmp() function should be treated as gone, and the cmp() special method is no longer supported. Use lt() for sorting, eq() with hash(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) – (a < b) as the equivalent for cmp(a, b).)

Text Vs. Data(binary) Instead Of Unicode Vs. 8-bit

Python 3.0 uses the concepts of text and (binary) data instead of Unicode strings and 8-bit strings. All text is Unicode; however encoded Unicode is represented as binary data. The type used to hold text is str, the type used to hold data is bytes. The biggest difference with the 2.x situation is that any attempt to mix text and data in Python 3.0 raises TypeError, whereas if you were to mix Unicode and 8-bit strings in Python 2.x, it would work if the 8-bit string happened to contain only 7-bit (ASCII) bytes, but you would get UnicodeDecodeError if it contained non-ASCII values.

You can no longer use u”…” literals for Unicode text. However, you must use b”…” literals for binary data.

As the str and bytes types cannot be mixed, you must always explicitly convert between them. Use str.encode() to go from str to bytes, and bytes.decode() to go from bytes to str. You can also use bytes(s, encoding=…) and str(b, encoding=…), respectively.

Like str, the bytes type is immutable. There is a separate mutable type to hold buffered binary data, bytearray. Nearly all APIs that accept bytes also accept bytearray. The mutable API is based on collections.MutableSequence.

All backslashes in raw string literals are interpreted literally. This means that ‘\U’ and ‘\u’ escapes in raw strings are not treated specially.

Tuples, Lists and Dictionaries in Python

1. Tuples:

Tuples are just like lists, but you can’t change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program. Again, each value is numbered starting from zero, for easy reference. Example: the names of the months of the year.


months = (‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’);

2. Lists

Lists are extremely similar to tuples. Lists are modifiable or mutable, so their values can be changed. Most of the time we use lists, not tuples, because we want to easily change the values of things if we need to.


//create names list

names = [‘Philip’, ‘Karan‘, ‘Mathew’];

//To add one more name

names. append(‘Thomas’);

//To remove a name


3. Dictionaries

Dictionaries are associative arrays. They have keys, and values. Just like a phone book, with people’s names and their numbers.


//create a phonebook

phonebook = {‘Philip’:4033224455, ‘Karan’:4033224456, ‘Mathew’:4033224457}

Benefits of Learning and Teaching Python to Students

Perl used to be considered a good first language to start training with, whether you were a teacher or student. But as other languages developed, and students and teachers alike were interested in object-oriented languages, then the game plan changed. It is generally more interesting to be able to see the object move as a result of your efforts. Some schools of thought preferred Java, thinking it to be a good learning tool as a first language, but Python is more flexible, and simpler by far than these other languages.


When a student or teacher begins the path to ‘enlightenment’ it can be very frustrating when you have errors you can’t find. Furthermore, the efficiency of Python causes people to get less bogged down. It is easy for a new teacher or student to get bogged down in errors that can’t be easily found, and one’s passion for the language can be lost. Not so with Python; you get to see the advantages right away from the results of your work, plus the language has new generation additions that make it even easier.

The last thing you want to do is become disillusioned with the first language regarding computer science. Since this is an introduction to the programming world for most people, they want it to be fun, which for a scripting language or programming language, Python manages to do. So like most intelligent academic planners, the strategy for the Educator is to approach the situation from a minimalist point of view making every attempt to assist the student. Finding that right balance that gives the student a taste for programming, and yet not overwhelming them is really the best approach to the study.

Lines of instructions are no longer necessary in order to get just a small function to happen in your scripting. If you have the happy fortune to create your own characters then you know the movement you are searching for, and it is a wonderful treat when you first accomplish it. This gives you the incentive and passion to want more and makes you look for other languages and learning to follow. For an instructor, a happy student that isn’t looking for the purely ‘academic’ is much easier to teach as well.

So, when the department considers how to guide the student, Python is great for inspiration of both students and instructors. Thus, a student comes to that next class eager to see what the new adventure in programming will be.