For the final portion, we will see some really useful string functions to work with strings in python. Below we have mentioned a few useful string functions.
len or length function is used to find the character length of any string.
len returns a number and it takes a string as an argument. For Example,
>>> s = "Hello" >>> len(s)
In case you want to find the position of any character or of a subString within any given string, you can use the
find function. It's implementation is a little different than a normal function but it's not tough to understand. Obviously to find a subString in a string, we will have to provide both the main string and the subString to be found, to the funtion. For Example,
>>> s = "Hello" >>> ss = "He" >>> print s.find(ss)
He is present at the beginning of the string
Hello, hence index
0 is returned as the result. It can be directly implemented/used as follows(in case you hate useless typing; which every programmer do):
>>> print "Hello".find("He")
lower() function is used to convert all the uppercase characters present in a string into lowercase. It takes a string as the function input, however the string is not passed as argument. This function returns a string as well.
>>> print "Hello, World".lower()
upper() is used to turn all the characters in a string to uppercase.
>>> print "Hello, World".upper()
islower() is used to check if
string_name string is in lowercase or not. This functions returns a boolean value as result, either
>>> print "hello, world".islower()
>>> print "Hello, World".islower()
isupper() is used to check if the given string is in uppercase or not. This function also returns a boolean value as result, either
>>> print "HELLO, WORLD".isupper()
>>> print "Hello, World".isupper()
replace() function will first of all take a string as input, and ask for some subString within it as the first argument and ask for another string to replace that subString as the second argument. For Example,
>>> print "Hello, World".replace("World", "India")
Suppose you're having a string say,
>>> mystring = "Hello World! Welcome to the Python tutorial"
Now we can use the
split() function to split the above declared string.
If we choose to split the string into two substring from the exclamation mark
!. We can do that by putting an exclamation mark
! in the character argument. It will basically split the string into different parts depending upon the number of exclamation marks
! in the string. All the sub-pieces of the string will be stored in a list. Like,
>>> print mystring.split("!")
['Hello World', ' Welcome to the Python tutorial']
You can store these values to another variable and access each element of it like this:
>>> myNEWstring = mystring.split("!") >>> print myNEWstring >>> print myNEWstring
Hello World Welcome to the Python tutorial
In the example below we have broken the string into 2 subStrings from a full stop