Original article was published by Ozan Güner on Artificial Intelligence on Medium
Most Common String Methods In Python
I would like to share with you some of the basic Python methods usage. While doing this I will use the lyrics of the song that I really loved when I was a teenager; “Bye Bye Bye” from N’SYNC..:)
Here is the part of the lyrics of the song…
Common String Methods To Use
- count( )
- len( )
- strip( )
- upper( )
- lower( )
- title( )
- capitalize( )
- replace( )
- split( )
My main aim is to calculate the percentage distribution of characters in string. But first let’s do some tricks with this lyrics by using Python methods;)
Using the count( ) method returned the number of times a specified value appears in the string. I would like to point out that Python is a case-sensitive programming language, so “B” is not same with “b”.
Using the len( ) method returned the number of whole characters in the string (including spaces and punctuation marks).
When I’d like to access to a specific character in string, I could use indexing and slicing. The index begins from “0” continues by incrementing 1 including the spaces and punctuation marks until the end of the string. I must also say that when I use indexing like “lyrics[0:33]”, it begins to be returned from 0 index value until the 33 (but 33rd index value is not being returned).
I removed the character that I setted into the strip ( ) method at the beginning and the end of the string (space is the default character to remove).
When I’d like to be returned all characters of the string to upper case, I use upper ( ) method.
If I’d like to be returned all characters of the string to lower case, I use lower ( ) method.
Either if I’d like to be returned the first character of each word in the string to upper case, I use title ( ) method.
And lastly, when I’d like to be returned the first character of the string to upper case, I use capitalize ( ) method.