Strings in Python

Strings in Python


String: is an ordered sequence of letters/characters. They are enclosed in single quotes („ ‟) or double („‟ “). The quotes are not part of string. They only tell the computer where the string constant begins and ends. They can have any character or sign, including space in them. These are immutable data types. We will learn about immutable data types while dealing with third aspect of object i.e. value of object.

Example

>>> a = 'Ram'

A string with length 1 represents a character in Python.

Conversion from one type to another

If we are not sure, what is the data type of a value, Python interpreter can tell us:

>>> type ("Good Morning")
<type "str">
>>> type ("3.2")
<type "str">

It is possible to change one type of value/ variable to another type. It is known as type conversion or type casting. The conversion can be done explicitly (programmer specifies the conversions) or implicitly (Interpreter automatically converts the data type).

For explicit type casting, we use functions (constructors):

  • int ()
  • float ()
  • str ()
  • bool ()

Example

>>> a= 12.34
>>> b= int(a)
>>> print b
12

Example

>>>a=25
>>>y=float(a)
>>>print y
25.0