Strings are nothing but simple text. In python we declare strings in between "" or '' or ''' ''' or """ """. The examples below will help you to understand sting in a better way.
>>> s = "I am Indian" >>> s 'I am Indian' >>> s = 'I am Indian' >>> s = "Here is a line \ ... splitted in two lines" >>> s 'Here is a line splitted in two lines' >>> s = "Here is a line \n splitted in two lines" >>> s 'Here is a line \n splitted in two lines' >>> print s Here is a line splitted in two lines
Now if you want to multiline strings you have to use triple single/double quotes.
>>> s = """ This is a ... multiline string, so you can ... write many lines""" >>> print s This is a multiline string, so you can write many lines
Every string object is having couple of buildin methods available, we already saw some of them like s.split(" ").
>>> s = "kushal das" >>> s.title() 'Kushal Das'
title() method returns a titlecased version of the string, words start with uppercase characters, all remaining cased characters are lowercase.
>>> z = s.upper() >>> z 'KUSHAL DAS' >>> z.lower() 'kushal das'
upper() returns a total uppercase version whereas lower() returns a lower case version of the string.
>>> s = "I am A pRoGraMMer" >> s.swapcase() 'i AM a PrOgRAmmER'
swapcase() returns the string with case swapped :)
>>> s = "jdwb 2323bjb" >>> s.isalnum() False >>> s = "jdwb2323bjb" >>> s.isalnum() True
Because of the space in the first line isalnum() returned False , it checks for all charecters are alpha numeric or not.
>>> s = "SankarshanSir" >>> s.isalpha() True >>> s = "Sankarshan Sir" >>> s.isalpha() False
isalpha() checkes for only alphabets.
>>> s = "1234" >>> s.isdigit() #To check if all the characters are digits or not True >>> s = "Fedora9 is coming" >>> s.islower() # To check if all chracters are lower case or not False >>> s = "Fedora9 Is Coming" >>> s.istitle() # To check if it is a title or not True >>> s = "INDIA" >>> s.isupper() # To check if characters are in upper case or not True
To split any string we have split(). It takes a string as an argument , depending on that it will split the main string and returns a list containing splitted strings.
>>> s = "We all love Python"
>>> s.split(" ")
['We', 'all', 'love', 'Python']
>>> x = "Nishant:is:waiting"
>>> x.split(':')
['Nishant', 'is', 'waiting']The opposite method for split() is join(). It takes a list contains strings as input and join them.
>>> "-".join("GNU/Linux is great".split(" "))
'GNU/Linux-is-great'In the above example first we are splitting the string "GNU/Linux is great" based on the white space, then joining them with "-".