Saturday, April 5, 2014

String simple utility functions in Python

There are many string utility functions which can reduce your code and increase performance.  Below are some of the methods.

To find the no.of occurances of a substring in a string in Python: count string method will return the no.of occurrences of a substring from a string. In the below example , 'M' occurrences are 22 and 'F' occurrences are 19, 'MF'  substring occurrence are 8 and 'FM' substring occurrences are 7

in_str = 'MFMMMFFMMMFFFMMMMMMMFFFFFMMFFMMFMFMMMFFFF'
print in_str.count('M')
print in_str.count('F')
print in_str.count('MF')
print in_str.count('FM')

Appending or concatenating strings in pythonjoin method connects strings with a separator. We can use same method for appending list of strings by using separator as space or empty. But join will work only on iterators like list. Below are some of the examples.

str_list = ['hello','how','are','you']
sentence = " ".join(str_list)
print sentence

OutPut:
hello how are you


str_list = ['hello','how','are','you']
sentence = "123".join(str_list)
print sentence

OutPut:
hello123how123are123you

As we can observe that , join method will take iterator as a input and combines with delimiter or separator and forms the string.


Finding ASCII value of a character in Python: To find the ASCII value of a character, use ord() function. Below is the syntax and example.


ascii_value = ord('a')
print ascii_value 

OutPut: 
97

Happy Reading!!!


No comments:

Popular Posts