Pages

Saturday, September 10, 2016

Python 2.7 Basic Examples

Python is very progressive programming language. It's widely used in many areas.

In this blog post of "Python tutorials" I post some basic examples that will help you to get some basic knowledge and understand Python syntax. These examples are for Python 2.7 version.


Simple use of print command

>>> print 'I am wealthy'
I am wealthy

Use of print command with 'a' variable

>>> a = 'I am wealthy'
>>> print a
I am wealthy

Join two variables with text in one sentence and print it

>>> a = 'I am'
>>> b = 'wealthy'
>>> print a + ' ' + b
I am wealthy

Multiply 'a' variable that contain text

>>> a = 'I am wealthy'
>>> print a*5
I am wealthyI am wealthyI am wealthyI am wealthyI am wealthy

Print more words at once

>>> print 'wealth', 'health', 'forgiveness'
wealth health forgiveness


Using '\' to separate two words with empty place

>>> print 'wealth\thealth'
wealth        health

Using '\n' to separate two words in two rows

>>> print 'wealth\nhealth'
wealth
health

Print a sentence that contain '

>>> print 'it\'s good to forgive'
it's good to forgive

Print a sentence that contain '

>>> 'it\'s good to forgive'
"it's good to forgive"

Print sentence surrounded by '

>>> print '\'I am wealthy\''
'I am wealthy'

Check if a word starts with certain alphabet/s

>>> 'wealth' .startswith('w')
True

>>> 'wealth' .startswith('n')
False

>>> 'wealth' .startswith('weal')
True

Check if a word ends with certain alphabet/s

>>> 'wealth' .endswith('h')
True

>>> 'wealth' .endswith('l')
False

>>> 'eal' in 'wealth'
True

>>> 'l' in 'health'
True

Check how many time some alphabet/s are in a sentence or words

>>> 'wealth health forgive good love humble smart'.count('h')
4

>>> 'wealth health forgive good love humble smart'.count('wealth')
1

Convert lower alphabets to upper

>>> 'wealth'.upper()
'WEALTH'

Convert upper alphabets to lower

>>> 'WEALTH'.lower()
'wealth'

Capitalize first alphabet in a word

>>> 'wealth'.capitalize()
'Wealth'

Capitalize each first alphabet in a list of words

>>> 'wealth health good'.title()
'Wealth Health Good'

Replace alphabet/s or word/s with others

>>> a = 'I am wealthy'
>>> a.replace('wealthy', 'healthy')
'I am healthy'

Replace empty spaces

>>> a = 'wealth health goodness forgiveness love'
>>> a.replace(' ', '')
'wealthhealthgoodnessforgivenesslove'

Other way to replace word/s
>>> a.replace('love', 'I').replace('good', 'forgive')
'I forgive'

1 comment:

  1. wonderful blogs! thankyou for sharing a realiable information for us and who is looking for a particular courses if any one want to learn python core to advance contact us on 9311002620 and visit our further websites https://www.htsindia.com/Courses/python/python-training-institute-in-south-delhi

    ReplyDelete