PYTHON 3 TUTORIAL FOR EVERYONE CHAPTER 3: STATEMENT | EXPRESSION | STRING

In this part of Python 3 series tutorial, we will discuss about what is statement in programming language? What is expression? We will finally discuss about how to use string variable in Python.

We have a video tutorial for this chapter for Bangla speaking people:

Statement:

In terms of programming language, the smallest unit of code which can be executed by Python interpreter is called statement. Some examples are:

print ("Hello World")
x = 2
x = 2 + 1
if x > 2:
print ("x is greater than 2")

Expression:

The combination of a value, operator and variables are called expression which evaluates a value. Some examples are:

x = 17
y = x + 2

String:

To declare string variable in Python we just define a name as variable and put sequence of characters within single or double quotes.

str1 = 'This is a string'
str2 = "This is also a string"

Accessing String Character

We can access string characters by positioning them from to 0 to the number of length. For example:

title = "Python Course"
print ( title[0], title[1], title[-1], title[-2])

output

P y e s

Here title[0], 0 position indicates the first character ‘P’ and title[1] indicates the second character ‘y’. In Python index position -1 indicates the last item of a sequence. So here title[-1] access the character ‘e’ and title[-2] access the character ‘s’ from the end of the string.

String Operation

String type has some built-in methods defined. For example, you can use upper() method to convert the characters into uppercase letters, lower() method to convert the characters into lowercase letters and title() method to convert first character of a word in a string to uppercase letter.

name = 'jonathon swift'
print ( name.title() )
print ( name.upper() )
print ( name.lower() )

output

Jonathon Swift
JONATHON SWIFT
jonathon swift

String Concatenation

Joining two or more strings into a single string is called concatenation. In Python we can use + operator for string concatenation.

first_name = "Steve"
last_name = "Jobs"
name = first_name + ' ' + last_name
print ( name )
print ( first_name + ' ' + last_name )

Output

Steve Jobs
Steve Jobs

Newline

We can use ‘\n’ newline character a backslash followed by n which executed as a newline between strings.

first_name = "Steve"
last_name = "Jobs"
print (first_name + "\n" + last_name)

Output

Steve
Jobs

Whitespace Remove

We can use some string object’s built-in methods to remove whitespace. If we use lstrip() which remove all the spaces leading of a string, if we use rstrip() that removes all the spaces of a trailing string. We can also call methods as method chaining like strobj.lstrip().rstrip(). But if we want to remove all the unnecessary spaces in both side of a string we can just use strip() method.

name = "        Mr. X        "
print('_' + name + '_')
print('_' + name.lstrip() + '_')
print('_' + name.rstrip() + '_')
print('_' + name.strip() + '_')
print('_' + name.lstrip().rstrip() + '_')

Output

_        Mr. X        _
_Mr. X _
_ Mr. X_
_Mr. X_
_Mr. X_

Single and Double Quotes

If we want to print a single quote ‘ within a string, the outside quotes should be double quotes when we define the string. Similarly if we want double quote ” inside a string, the outside quotes should be single quotes when we define the string. But if we want the outside quotes should be single quotes and the inside as well, we can use \’ escape sequence to put single quote inside a string. This rules also applies for double quotes as well.

shop_name = "Rahim's Shop"
print(shop_name)
shop_name = 'Rahim"s Shop'
print(shop_name)
shop_name = 'Rahim\'s Shop'
print(shop_name)

Output

Rahim's Shop
Rahim"s Shop
Rahim's Shop

Matching text at the end and start

If we want to check whether a string data begins by some characters or ends by some characters, we can use startswith() and endswith() methods of a string.

filename = 'bigdata.txt'
print ( filename.endswith('.txt') )
print ( filename.startswith('bi') )

Output

True
True

Searching word in a sentence

If we want to search word in a sentence we can easily do it by find() method of string.

sentence = "A quick brown fox jumps over the lazy dog"
print ( sentence.find('fox') )
print ( sentence.find('foxs') ) # -1 the valu not found

Output

14
-1

Replace text in a string

If we want to replace a word by another word we can easily do it by replace() method.

sentence = "A quick brown fox jumps over the lazy dog"
sentence = sentence.replace('fox', 'tiger')
print ( sentence )

Output

A quick brown tiger jumps over the lazy dog

Print function separator

To separate words within a print statement we can do the following. Either we can concatenate by + operator or we can use sep parameter of print function.

x = 'Dhaka'
y = 'Bogra'
z = 'Comilla'
print (x + '| ' + y + '| ' + z)
print (x, y, z, sep='| ')

Output

Dhaka| Bogra| Comilla
Dhaka| Bogra| Comilla

String interpolation

String interpolation means evaluates a variable data within a string object. There are several ways to accomplish this task. The most common way is to use {varaiable_name} inside a string and later use format() method to pass the real value. Another way is to use ‘%s’ or ‘%d’ like the C language modifiers. In the following example of the first part, we use {name} and format() method of keywords arguments for string interpolation.

person = '{name}\'s age is {age}'
print(person.format(name='Bill', age=55))
print(person.format(name='Steve', age=50))
person = '%s\'s age is %d'
print(person % ('Bill', 55) )

Output

Bill's age is 55
Steve's age is 50
Bill's age is 55

String slicing

Using a range operator we can slice string in python easily. In the following example, when we use name[0:6] it means get the sequence of characters from 0 to 5 position. Here though we mentioned 6 but 6 is not inclusive, it will take 6–1 position as string characters. If we omit the first name[:6] in range operator, python automatically assign 0 for it. Similarly if we mention name[7:] it means from 7th position take all the characters till the end of the string. And if we use -1 it means till the characters before the last character. -1 means position starts from the end side.

name = "Taylor Swift"
print (name[0: 6])
print (name[:6])
print (name[7:])
print (name[7:-1])

Output

Taylor
Taylor
Swift
Swif

Github Code

https://github.com/mahmudahsan/thinkdiff/blob/master/python/chapter3.py

Thank you for reading the post

Originally Published: thinkdiff.net

Written by

Programmer | Writer | Traveller → https://thinkdiff.net

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store