Python ProgrammingPython Programming

1) How do I trim white space?

##
# Python function that will trim whitespace (spaces and tabs) from a string
 
string_var = "  \t a string example\n\t\r  "
print(string_var)
 
string_var = string_var.lstrip()  # trim white space from left
print(string_var)
 
string_var = "  \t a string example\t  "
string_var = string_var.rstrip()  # trim white space from right
print(string_var)
 
string_var = "  \t a string example\t  "
string_var = string_var.strip()  # trim white space from both side
print(string_var)
Sample output of above program, shown as below:
How do I trim white space?

2) Different ways to pad/add zeroes to string

##
# Python program to add a numeric string with zeroes.
 
num = 7
 
print('{0:0>5d}'.format(num))  # left
print('{0:0<5d}'.format(num))  # right
 
print('{:05d}'.format(num))
 
print("%0*d" % (5, num))
print(format(num, "05d"))
 
temp = 'test'
print(temp.rjust(10, '0'))
print(temp.ljust(10, '0'))
Sample output of above program, shown as below:
Different ways to pad zeroes to string

3) How to check if the string is empty or blank?

##
# Python program to test empty or blank string
 
test_string = ""
 
# Example 1
if not test_string:
    print("Empty")
else:
    print("Not Empty")
 
# Example 2
if test_string:
    print("Not Empty")
else:
    print("Empty")
 
# Example 3 check blank string
blank_string = " \t"
 
if blank_string.strip():
    print("Not Empty")
else:
    print("Empty")
 
Sample output of above program, shown as below:
How to check if the string is empty or blank?

4) Different ways to count the number of occurrences of a character in a string

##
# Python program to count the number of occurrences of a character in a string
 
import re
from collections import Counter
 
sentence = 'Canada is located in the northern part of North America'
# Example I
counter = len(re.findall("a", sentence))
print(counter)
 
# Example II
counter = sentence.count('a')
print(counter)
 
# Example III
counter = Counter(sentence)
print(counter['a'])
 
Sample output of above program, shown as below:
Different ways to count the number of occurrences of a character in a string

5) How to compare strings in Python using either '==' or 'is'?

The is keyword is a test for object identity while == is a value comparison. If you use is, the result will be true if and only if the object is the same object. However, == will be true any time the values of the object are the same.

##
# Python program to compare two strings
 
str1 = "Canada"
str2 = "Canada"
print(str1 is str2)  # True
print(str1 == str2)  # True
 
string1 = ''.join(['Ca', 'na', 'da'])
string2 = ''.join(['Can', 'ada'])
print(string1 is string2)  # False
print(string1 == string2)  # True
 
Sample output of above program, shown as below:
Comparing strings in Python using either '==' or 'is'

6) How to Split Strings on Multiple Delimiters or specified characters?

##
# Python program to Split Strings on Delimiters or specified characters
 
 
# Example 1
import re
string_test = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
print(re.findall(r"[\w']+", string_test))
 
 
# Example 2
def split_by_char(s, seps):
    res = [s]
    for sep in seps:
        s, res = res, []
        for seq in s:
            res += seq.split(sep)
    return res
 
print(split_by_char(string_test, [' ', '(', ')', ',']))
 
Sample output of above program, shown as below:
How to Split Strings on Multiple Delimiters or specified characters

7) How do I append one string to another?

##
# Python program to append one string to another
 
# Example 1
str1 = "Can"
str2 = "ada"
str3 = str1 + str2
print(str3)
 
# Example 2
str4 = 'Ca'
str4 += 'na'
str4 += 'da'
print(str4)
 
# Example 3
join_str = "".join((str1, str2))
print(join_str)
 
# Example 4
str_add = str1.__add__(str2)
print(str_add)
 
Sample output of above program, shown as below:
C:\programs\string>pep8 --first example7.py

C:\programs\string>python example7.py
Canada
Canada
Canada
Canada

C:\programs\string>

8) How do I iterate over a string in Python?

##
# Python program to iterate over a string.
 
# Example 1
test_str = "Canada"
for i, c in enumerate(test_str):
        print(i, c)
 
print("------------------------")
 
# Example 2
indx = 0
while indx < len(test_str):
        print(indx, test_str[indx])
        indx += 1
 
print("------------------------")
# Example 3
for char in test_str:
        print(char)
 
Sample output of above program, shown as below:
C:\programs\string>pep8 --first example8.py

C:\programs\string>python example8.py
0 C
1 a
2 n
3 a
4 d
5 a
------------------------
0 C
1 a
2 n
3 a
4 d
5 a
------------------------
C
a
n
a
d
a

C:\programs\string>

9) How to strip punctuation from a string in Python?

##
# Python program to remove punctuation from a string.
 
import string
import re
 
# Example 1
s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
out = re.sub(r'[^\w\s]', '', s)
print(out)
 
# Example 2
s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
for p in string.punctuation:
        s = s.replace(p, "")
print(s)
 
# Example 3
s = "Ethnic (279), Responses (3), 2016 Census - 25% Sample"
out = re.sub('[%s]' % re.escape(string.punctuation), '', s)
print(out)
 
Sample output of above program, shown as below:
C:\programs\string>pep8 --first example9.py

C:\programs\string>python example9.py
Ethnic 279 Responses 3 2016 Census 25 Sample
Ethnic 279 Responses 3 2016 Census 25 Sample
Ethnic 279 Responses 3 2016 Census 25 Sample

C:\programs\string>

10) How to convert a list into string?

##
# Python program to convert a list into a string
 
list_exp = ['Ca', 'na', 'da']
print(type(list_exp))
 
# Example 1
str_exp1 = ''.join(list_exp)
print(type(str_exp1))
print(str_exp1)
 
# Example 2
str_exp2 = ''.join(str(e) for e in list_exp)
print(type(str_exp2))
print(str_exp2)
 
# Example 3
str_exp3 = ''.join(map(str, list_exp))
print(type(str_exp2))
print(str_exp2)
 
Sample output of above program, shown as below:
How to convert a list into string'

11) Sort a list of strings

##
# Python program to Sort a list of strings
 
 
# Example 1
str_list = ["Japan", "Canada", "Australia"]
print(str_list)
str_list.sort()
print(str_list)
 
# Example 2
str_list = ["Japan", "Canada", "Australia"]
for x in sorted(str_list):
    print(x)
 
# Example 3
str_var = "Canada"
strlist = sorted(str_var)
print(strlist)
 
Sample output of above program, shown as below:
C:\programs\string>pep8 --first example11.py

C:\programs\string>python example11.py
['Japan', 'Canada', 'Australia']
['Australia', 'Canada', 'Japan']
Australia
Canada
Japan
['C', 'a', 'a', 'a', 'd', 'n']

C:\programs\string>

12) Convert Json into String

##
# Python program to Convert Json into String
 
import json
# list with dict a simple Json format
json_exp = \
    [{"id": "12", "name": "Mark"}, {"id": "13", "name": "Rock", "date": None}]
print(type(json_exp))
 
str_conv = json.dumps(json_exp)  # string
print(type(str_conv))
print(str_conv)
 
Sample output of above program, shown as below:
Convert Json into String

13) Generate list of alphabets

##
# Python program to generate list of alphabets
 
 
def letter_range(start, stop, step=1):
    start = ord(start.lower())
    stop = ord(stop.lower())
    for str_lst in range(start, stop, step):
        yield chr(str_lst)
 
print(list(letter_range("a", "f")))
print(list(letter_range("m", "z", 2)))
 
Sample output of above program, shown as below:
C:\programs\string>pep8 --first example13.py

C:\programs\string>python example13.py
['a', 'b', 'c', 'd', 'e']
['m', 'o', 'q', 's', 'u', 'w', 'y']

C:\programs\string>

14) How to check whether a string starts with XXXX in Python?

##
# Python program to check whether a string starts with XXXX
 
import re
 
exp_str = "Python Programming"
 
# Example 1
if re.match(r'^Python', exp_str):
    print(True)
else:
    print(False)
 
# Example 2
result = exp_str.startswith("Python")
print(result)
 
Sample output of above program, shown as below:
C:\programs\string>python example14.py
True
True

C:\programs\string>pep8 --first example14.py

C:\programs\string>

15) Different ways to mesh or interleave two strings together in Python

##
# Python program to mesh two strings
 
str1 = "AAAA"
str2 = "BBBBBBBBB"
 
# Example 1
mesh = "".join(i + j for i, j in zip(str1, str2))
print("Example 1:", mesh)
 
# Example 2
min_len = min(len(str1), len(str2))
mesh = [''] * min_len * 2
mesh[::2] = str1[:min_len]
mesh[1::2] = str2[:min_len]
print("Example 2:", ''.join(mesh))
 
# Example 3
mesh = ''.join(''.join(item) for item in zip(str1, str2))
print("Example 3:", mesh)
 
# Example 4
min_len = min(len(str1), len(str2))
mesh = [''] * min_len * 2
mesh[::2] = str1[:min_len]
mesh[1::2] = str2[:min_len]
mesh += str1[min_len:] + str2[min_len:]
print("Example 4:", ''.join(mesh))
 
Sample output of above program, shown as below:
C:\programs\string>pep8 --first example15.py

C:\programs\string>python example15.py
Example 1: ABABABAB
Example 2: ABABABAB
Example 3: ABABABAB
Example 4: ABABABABBBBBB

C:\programs\string>

16) How to check if string ends with one of the strings from a list?

##
# Python program to check if string ends with one of the strings from a list
 
str_list = ['aaa', 'bbb', 'ccc', 'ddd']  # list of items
str_test = 'testccc'  # string need to test
 
for str_item in str_list:
    if str_test.endswith(str_item):
        print("found")
        break   # loop ends when result found
    else:
        print("not found")
 
Sample output of above program, shown as below:
C:\programs\string>pep8 --first example16.py

C:\programs\string>python example16.py
not found
not found
found

C:\programs\string>