Python [Post 04] | Strings

Folks,

In this blog post we will explore Python strings & string methods. Python strings are sequences of characters. Here are some examples of strings.

# Printing String

print('This is a string!') # Enclosed using single quote

print("This is also a string!") # Enclosed using double quote

print("""This is also a string,
also having next line.""") # Enclosed using triple quote. Multiple lines are generally put in triple quotes.

print("It's ok!") # Use double quote to enclose the string, if string is having single quote
print('P') # Python treat this single character also as string

This is a string!
This is also a string!
This is also a string,
also having next line.
It’s ok!
P

### String Indexing

Python strings are sequences of individual characters. We can access characters in strings by index. In Python index starts from 0, also if you want to start from the end, instead of the beginning then use a negative index.

Indexing Example: String x = ‘Python’

+ve Index 0 1 2 3 4 5
+ve Index 0 -5 -4 -3 -2 -1

# String Variable
x = 'Python'
x[0] # Fetch the first character of string x

‘P’

x[1] # Fetch the second character of string x

‘y’

x[-1] # Fetch the last character of string x

‘n’

Python strings are immutable. i.e. Once string is created, the elements within it can not be changed or replaced.

# Let's try to change the first letter to 'J' of string x
x[0] = 'J'

TypeError Traceback (most recent call last)

<ipython-input-6-5b400f918714> in <module>()
1 # Let’s try to change the first letter to ‘J’ of string x
—-> 2 x[0] = ‘J’

TypeError: ‘str’ object does not support item assignment

 

You can “update” an existing string by (re)assigning a variable to another string.

x = 'J' + x[1:]
print(x)

Jython

### Slicing Python String

We can use a : to perform slicing which extracts chunk of more than one character as per input. In slicing last index is not included.

String x = ‘Python’

+ve Index 0 1 2 3 4 5

+ve Index 0 -5 -4 -3 -2 -1

For Example:

# String Variable
x = 'Python'
x[0:2] # fetch the first 2 character of string x. x[0:2] is same as x[:2]

‘Py’

x[:3] # fetch the first 3 character of string x

‘Pyt’

x[2:5] # fetch character from 2nd index to 3rd index

‘tho’

x[2:] # fetch charcters start from index 2nd till last

‘thon’

x[:3] # fetch charcters upto 3rd index, but 3rd is not included

‘Pyt’

x[-5:-1] # Negative Index also works in slicing

‘ytho’

x[::] # fetch complete string

‘Python’

Skipping Characters using third parameter

x = 'Python'
x[::1] # Default is 1

‘Python’

x[::2] # Skip every 2nd character

‘Pto’

x[0:5:2] # Skip every 2nd character

‘Pto’

x[::-1] # Reverse String

‘nohtyP’

### String Methods Examples

Python String provides so many methods to do the string manipulations. See below examples.

# Split - Splits string as per provided delimiter ( default space) and returns list of substrings;

x = 'Python is fully-functional programming language that can do almost anything'
print(x.split())

[‘Python’, ‘is’, ‘fully-functional’, ‘programming’, ‘language’, ‘that’, ‘can’, ‘do’, ‘almost’, ‘anything’]

x = 'A,B,C,D,E,F'
print(x.split(',')) # Comma as delimeter

[‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’]

# Upper & Lower Case

x = 'Python'
print(x.upper())
print(x.lower())

PYTHON
python

# Checking String whether contains only alpha or numeric

x = 'Python3'
print(x.isalnum())
print(x.isalpha())
print(x.isnumeric())
len(x)

True
False
False
7

Lstrip, RStrip & Strip Method – For removing white spaces

# lstrip - Remove white space from left

x = ' Python3 '
x.lstrip()

‘Python3 ‘

# rstrip - Remove white space from left

x = ' Python3 '
x.rstrip()

‘ Python3’

# rstrip - Remove white space from left & right

x = ' Python3 '
x.strip()

‘Python3’

.format() String Method

Insert objects dynamically in the string using assigment keywords or index. It can also persorm alignment, padding & precision of floating point numbers.

import datetime
d = str(datetime.datetime.now())
# Example 1 -

x = "Today's date & time is {}"

x.format(d)

“Today’s date & time is 2018-07-08 02:04:47.893499”

# Example 2

x = "Today's date & time is %s" %datetime.datetime.now()

print(x)

Today’s date & time is 2018-07-08 02:04:49.885035

# Example 3

print('a {f} in need is a {f} indeed'.format(f='friend'))
print('a {0} in need is a {0} indeed'.format('friend'))

a friend in need is a friend indeed
a friend in need is a friend indeed

# String Formatting Operator - %
# Oldest method involves placeholders using the modulo % character. %s for string, %c is for character, %i integer, %f float etc

print('a %s in need is a %s indeed' %('friend','friend'))

x = "Today's date & time is %s" %datetime.datetime.now()
print(x)

x = "My name is %s, my age is %i & my height is %f" % ('John', 21, 150.56)
print(x)

a friend in need is a friend indeed
Today’s date & time is 2018-07-08 02:04:50.634701
My name is John, my age is 21 & my height is 150.560000

Precision of Float with .format() Method

You can add precision for float point numbers in string. See below example.

x = “My height is %5.1f” % (150.5678)

  • .1f stands for how many numbers to show past the decimal point.
  • 5 would be the minimum number of characters the string should contain. Padded with whitespace if the entire number does not have this many digits.
x = "My height is %5.1f" % (150.5678)
print(x)

My height is 150.6

x = "My height is %15.2f" % (150.5678)
print(x)

My height is 150.57

Padding & Alignment with .format() Method

# Padding

print('{0:5} | {1:3}'.format('FName', 'Age'))
print('{0:5} | {1:3}'.format('A', 14))
print('{0:5} | {1:3}'.format('B', 12))

FName | Age
A | 14
B | 12

By default, .format() aligns text to the left, numbers to the right.
Pass an optional <,^, or > to set a left, center or right alignment as per requirement.

# Alignment

print('{0:^5} | {1:^3}'.format('FName', 'Age'))
print('{0:^5} | {1:^3}'.format('A', 14))
print('{0:^5} | {1:^3}'.format('B', 12))

FName | Age
A | 14
B | 12

print('{0:-^10} | {1:-^10}'.format('FName', 'Age'))

–FName— | —Age—-

There are many more string methods eg. count, find, decode, encode, index etc.


Thanks!

Happy Learning! Your feedback would be appreciated!
shobhitsingh.in

[GitHub Code]

Advertisements

Python [Post 02] | Variables

In Python a variable is created when we assign value to it. It does not required any explicit declaration. Use the assignment operator = to assign the value to a variable.

Variable Names Rules

  • Must start with a letter or the underscore character. Cannot start with a number.
  • Can only contain alpha-numeric characters and underscores (A-z, 0-9, & _ ).
  • Variable names are case-sensitive.
  • Avoid using Python Built-keywords. Like str, type, list etc.
#Example:

name = "John" # String Variable Assignment
age = 50 # Integer Variable Assignment
height = 150.50 # Float Variable Assignment

Using Python’s built-in function type() you can check what type of object is assigned to a variable.

Here are the list of Python data type:

  • int
  • float
  • str
  • list
  • tuple
  • dict
  • set
  • bool
# Exapmple

type(name)

str

## Dynamic Typing

In Python you can reassign variables to different data types. Python is very flexible in assigning data types.

# Example, Here Integer Assignment

x=50
type(x)

int

x="Hello, World!" # Re-assigned X Now String Assignment
type(x)

str

x=12.20+4j # Re-assigned X Now String Assignment
type(x)

complex

x=(1,2,3,4,5) # Re-assigned X Now Tuple Assignment
type(x)

tuple

## Re-assigning Variables

Python allow you to reassign variables with a reference to the same object.

a=50
print(a)

50

a = a + a
print(a)

100

a += 50
print(a)

150

a -= 10
print(a)

140

a *= 2
print(a)

280

a /= 5
print(a)

56.0

# Multiple Assignment

Python allows you to assign a value to multiple variables simultaneously.

# Example 1

length = width = height = 50
print (length)
print (width)
print (height)

50
50
50

# Example 2

length, width, height = (10,50,60)
print (length)
print (width)
print (height)

10
50
60


Thanks!

Happy Learning! Your feedback would be appreciated!

shobhitsingh.in

GitHub Code

Python [Post 03] | Numbers

Folks,
In this blog we will explore different Python numeric types, arithmetic operations, mathematical fuctions, variable assignment & number conversion.

For Python Overview & Basic – Refer this Blog Post

Python has mainly three diffrent of numeric types.

  • int
  • float
  • complex

Integers (int)


Int/Integer, is basically a whole number (+ve or -ve), without decimals & of unlimited length.

Example of Integers: -5, 500, 20001543646546231654646465465454544545454554

 

# Integer Example 1
print(-5)
type(5)

-5
int

# Integer Example 2
print(500)
type(500)

500
int

# Integer Example 3
print(20001543646546231654646465465454544545454554)
type(20001543646546231654646465465454544545454554)

20001543646546231654646465465454544545454554
int

Float


Floating point numbers is a number, (+ve or -ve), represent real numbers and they have a decimal points in them, or use an exponential (e) to define the number.

Exampe of Floats: -5.5 , 500.5, 5E2

5E2 (5 times 10 to the power of 2) is also an example of a floating point number in Python.

# Float Example 1
print(-5.5)
type(-5.5)

-5.5
float

# Float Example 2
print(500.5)
type(500.5)

500.5
float

# Float Example 3
print(5E2)
type(5E2)

500.0
float

Complex Number


Numbers in the form of (a + bj), where a and b are floats and j represents the square root of -1. Real part of the number is a, and the imaginary part is b.

Exampe of Complex Number: 5+500j

# Complex Example 1
5+500j

(5+500j)

type(5+500j)

complex

Artithmetic Operations


# Additon of numbers
5+5

10

# Substraction of numbers
10-5

5

# Multiplication of numbers
10*5

50

# Division of nuumbers
10/5

2.0

# Floor Divison (// operator truncates the decimal without rounding)
10//4

2

# Exponent
5**2

25

# Modulus (% operator returns the remainder after division)
5%2

1

Mathematical Fuctions


Python also have some functions that perform mathematical calculations

# importing "math" for mathematical operations
import math
# Ceil Function
print (math.ceil(5.6))

6

# Floor Function
print (math.floor(5.6))

5

# Exponential Function
print (math.exp(5))

148.4131591025766

# Square Root Function
print (math.sqrt(16))

4.0

# Factorial Function
print (math.factorial(5))

120

# Absolute Function - Positive Number
print(abs(-5))

5

# Round Function - Number rounded to n digits from the decimal point
print(round(5.56))

# Round Function with 2nd argument for how many digits to round
print(round(5.56,1))

6
5.6

# Minimun Function - Finds smallest of its arguments
print (min(5,10,2,22))

2

# Mamimun Function - Finds largest of its arguments
print (min(5,10,2,22))

2

Variable Assignemnt


# Create an object/Variable called "length" and assign it the number 50
length = 50
print(length)

50

# Reassignment - Overrites value
length = 10
print(length)

10

length = 10
width = 5.6
height = 10.6

print(length * width * height)

593.6

Numerical Type Conversion


# Example 1:
height = 10.6
type(height)

float

# Let's convert this variable into int
height= int(height)
print(height)
type(height)

10
int

# Example 1:
length = 10
type(length)

int

# Let's convert this variable into foat
length= float(length)
print(length)
type(length)

10.0
float


Thanks!

Happy Learning! Your feedback would be appreciated!

shobhitsingh.in
Guthub Code

Python [Post 1] | Overview & Basics

What is Python? 

python-logo.png

Python is a general purpose object-oriented programming language with high-level programming capabilities. Developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands.

  • Open Source general-purpose programming language.
  • High-level programming language (i.e. independent of the computer’s hardware).
  • Interpreted (i.e. not need to compile your program before executing it, Python is processed at run-time by the interpreter)
  • Multiple Programming Paradigms ( i.e. Python supports object oriented programming, imperative and functional programming or procedural styles)
  • Code Readability – Python is easy to read, write & maintain.
  • Interactive –   IDLE is Python’s built-in Integrated Development Environment. It has a Python shell window, which gives you access to the Python interactive mode.

Python is fully-functional programming language that can do almost anything.

You can install latest Python from this website – https://www.python.org/

Please see below YouTube video for Python Installation on you Windows Machine in 2 minutes.

After installation you can check the Python Version using Command Prompt.

1.PNG

Hello, World! in Python programming.

print("Hello World!")

2.PNG


Thanks!

Happy Learning! Your feedback would be appreciated!