Python 3-Variable

Python Variable

The Python variable is a reserved memory location to store values. Every value in a Python program has a data type. The data types in Python are int, float, String and compelx numbers. Other data types for python are Tuples, List, Strings and Dictonary.

Example  

>>> x=10
>>> y=x+20
>>> print (y)
30
>>>

In the above example, the value ‘x’ is assigned to the number 10, the python interpreter reads the number 10 as a integer itself. Let see how it stores the float variable.

>>> x=10.0
>>> y = x+20
>>> print (y)
30.0
>>>

When the decimal is assigned, the Python interpreter read the value as a Float variable and the addition operation carried out with int or float and float variable is returned.

Python Type Casting

Python casting is a simple process to convert one data type into another with basic functions such as int(), float() or str(). Lets see with the below example

>>> x=10
>>> type(x)
<class 'int'>
>>> str(x)
'10'
>>> float(x)
10.0
>>>

In the above example, the integer variable ‘x’ is type casted to string and float. 

Python String

The Python String is a sequence of characters, either as a literal constant or some kind of variable. String literals in Python is either covered by single quotations marks or double quotation marks.

‘hello’ is same as “hello”

Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, the single character is simply a string.

>>> a = "Spark DataBox"
>>> print (a)
Spark DataBox
>>> print (a[1])
p
>>>

Python String Functions

Python String has a various functions to play around with the String variable such as

  • substring
  • strip()
  • len()
  • lower()
  • upper()
  • replace()
  • split()

substring() – Get the variable from the position 2 to 6 (not included):

>>> a = "Spark DataBox"
>>> print(a[2:6])
ark
>>>

strip() – It removes all the white spaces from beginning or end of the String:

>>> a = "  Spark DataBox  "
>>> print(a.strip())
Spark DataBox

len() – It returns the length of the String:

>>> a = "Spark DataBox"
>>> print(len(a))
13
>>>

lower() – This method returns the String in lower case:

>>> a = "Spark DataBox"
>>> print(a.lower())
spark databox
>>>

upper() – This method returns the String in upper case:

>>> a = "Spark DataBox"
>>> print(a.upper())
SPARK DATABOX
>>>

replace() – It replaces the string with another string as show below:

>>> a = "Hello, World!"
>>> print(a.replace("H", "J"))
Jello, World!
>>>

split()  This method splits the string into substrings if it finds the instances of the separator

>>> a = "Hello, World!"
>>> print(a.split(","))
['Hello', ' World!']
>>>