Python Strings

Strings is a sequence type, sequence collection or group of things together.

Key characteristics

Strings can be numerical or alphanumerical, and also they are immutable. Immutable means that once you create a string you can't change it. Strings are homogeneous, which means that they can only take alphanumeric characters.

What to use it for

We use string to hold information.

>>> variable = "string" ''' Strings is everything between double quotes regardless of what it has '''
>>> variable
>>> print variable   ''' print is an external method give us the string representation'''

Now we play with integers

>>> number=23
>>> print number   ''' We get a string representation of the integer'''

Functions that applies to strings

We can convert an integer to a string using the str() function. This takes what was a number and make it a string.

>>> str(number)    ''' Using the str() function we change the numerical value into a string'''

We can know the number of elements using the len() function.

>>> len(variable)
>>> len(variable[0:3])
>>> len(number)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> len(str(number))

To take out different pieces or access individual elements we apply the slice notation. We can define as subsets of the sequence. This notation is a bracket and establish a minimum to a maximum of elements which we want to take out.

>>> variable[0:1]
>>> variable[2:100]

Python is a 0 offset language that means that it start from 0 instead of 1. Strings are a group of elements, so the first element will be the 0 element. So in a 10 element string the first will be 0 and the last will be 9. So we can point to the index we want based on this sequence:

>>> variable[0]
>>> variable[1]
>>> variable[2]


We can modify the string by using methods, one of this methods would be to capitalize() or to make all uppercase we can call on upper() method.

>>> print variable.capitalize()
>>> print variable.upper()
>>> print 

Similar to slice, we can use split() method however split will go on parsing the string based on the white spaces. So if the value have spaces split will come through.

>>> sentence = "My name is Earl"
>>> sentence.split()
['My', 'name', 'is', 'Earl'] 

The opposite of split() will be the 'join() method which will join different elements. This is most commonly used on the Python Lists page.

>>> lst = ['here','is','a','list','of','words']
>>> print '-+-'.join(lst)
>>> print ' '.join(lst)
here is a list of words