Python – Numbers & Strings

This post is the fourth of many that attempts to document everything I have been learning about Python.

Python is dynamically typed, there are no type declarations. It keeps track of types for you and is a strongly typed language. Types are created when expressions are evaluated. Only operations valid on a type can be performed on it.

Python provides built-in object types that you can start using in your programs right away. Objects like lists, dictionaries, tuples and strings are part of the core language.

In most cases, these built-in objects are all that you need to model your application domain. Moreover, these objects are implemented using C which means you get a good deal of performance by using them.

In cases where you have to define your own, Python allows you to define your own types which can in turn leverage the functionality provided by Python’s core built-in objects.

Python types are either immutable (cannot be changed in place) or mutable (can be changed in place).

Strings, numbers, tuples, sets are immutable.

Lists & Dictionaries are mutable.

Numbers

Numbers in python  are integers, floating point numbers, fixed precision decimals, complex and rational numbers.

In 3.0 integers can hold values no matter how large, in 2.6 a separate long integer type holds values that are beyond the range of integers.

Strings

Strings in Python are positional ordered collection of single characters. They are part of the family of sequences. You can operations like index and slice on them.

Indexing a string:

>>>
>>> # string in Python
>>> day_job = ‘human genome project
>>>
>>> # indexing a string to retrieve the
>>> # character at the index (offset)
>>>
>>> day_job[0]
h
>>>
>>> # Negative offsets can be used
>>> # start from the end of the string
>>>
>>> day_job[-1]
t
>>>

Slicing a string:

You can extract parts of a string by slicing it. The syntax is val[i:j] where i is the starting offset and the string is sliced all the way up to but not including offset j

>>>
>>> day_job = “human genome project
>>>
>>> # slicing a string
>>> day_job[6:12]
genome
>>>

You can slice using negative offsets. If you skip the indexes all together, they default – 0 for the lower bound and the length of the string for the upper bound.

>>> day_job = “human genome project
>>>
>>> # slicing a string
>>> # using negative offsets
>>> day_job[0:-3]
human genome proj
>>>
>>> # slicing a string
>>> # using offset defaults
>>> day_job[:-7]
human genome
>>> day_job[5:]
genome project
>>>

The indexing and slice operations are built in Python operations and are applicable to any type that is a sequence.

You can apply operations on strings. + is used to concatenate strings, whereas a * will repeat the string a certain number of times.

>>>
>>> # concatenation
>>> “day” + ” job
day job
>>>
>>> # repetition
>>> “day job” * 3
day jobday jobday job
>>>

Operations that are type specific are available as callable methods on that type.

>>>
>>> day_job = “human genome project
>>>
>>> # returns the index of the string
>>> # location of the string.
>>> day_job.find(‘genome‘)
6
>>>
>>> # replaces the old value with the new one
>>> day_job.replace(‘project‘, ‘assignment‘)
human genome assignment
>>>

To get a list of all string methods, you can use the dir method by passing in the type as parameter. You can then invoke the help method by passing the type and its attribute to learn more about its usage.

>>>
>>> day_job = “human genome project
>>> dir(day_job)
[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__doc__‘, ‘__eq__‘,
__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__getnewargs__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__iter__‘, ‘__le__‘,
__len__‘, ‘__lt__‘, ‘__mod__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__rmod__‘, ‘__rmul__‘,
__setattr__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘,
_formatter_field_name_split‘, ‘_formatter_parser‘, ‘capitalize‘, ‘center‘, ‘count‘, ‘encode‘, ‘endswith‘, ‘expandtabs‘, ‘find‘, ‘format‘,
index‘, ‘isalnum‘, ‘isalpha‘, ‘isdecimal‘, ‘isdigit‘, ‘isidentifier‘, ‘islower‘, ‘isnumeric‘, ‘isprintable‘, ‘isspace‘, ‘istitle‘, ‘isupper‘,
join‘, ‘ljust‘, ‘lower‘, ‘lstrip‘, ‘maketrans‘, ‘partition‘, ‘replace‘, ‘rfind‘, ‘rindex‘, ‘rjust‘, ‘rpartition‘, ‘rsplit‘, ‘rstrip‘, ‘split‘,
splitlines‘, ‘startswith‘, ‘strip‘, ‘swapcase‘, ‘title‘, ‘translate‘, ‘upper‘, ‘zfill‘]
>>>
>>> help(day_job.upper)
Help on built-in function upper:

upper(…)
S.upper() -> str

Return a copy of S converted to uppercase.

>>>

You can create strings using string literals, string format expressions, string format functions (new in version 3.x), strings with special characters, multiline strings that are printed as-is created using 3 quotes (either single or double).

The string type in 3.x is used to handle both regular ASCII and Unicode characters.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s