Monday, 12 June 2017

How to use Split() Method in python | Softcrayons IT Training Tutorial



Today we will learn about split() method in python which is very useful in our programming.


Syntax


str.split([x,num])


Parameters


  • X – the character after which you want to break the
    value. It can be any character you want and default it takes space as
    it argument.
  • num- this is number of lines to be made
Example


a=”the way you see people is the way they became”


printa.split()


printa.split(” “,1)








The above program will show following output


[‘the’, ‘way’, ‘you’, ‘see’, ‘people’, ‘is’, ‘the’, ‘way’, ‘they’, ‘became’]


[‘the’, ‘way you see people is the way they became’]





This would be more understood by a practical example. Suppose
you need to make a program that should take comma as a separator and
find the length of words. Means after comma it should consider every
value separated.



So in this program we will take user input and it should separate values by a comma.


b = raw_input(“Please enter a list of strings(seperated by a comma): “)


y = []                              # empty list in which length of words will be stored


x = b.split(“,”)               #     so the user input can be separated by a comma


fori in x:                       # for taking each value individually


a = len(i)                 # it will count the length of word


y.append(a)           # it will insert data in list “y” automatically


print y





So when we will run the program it will give following result





Please enter a list of strings(seperated by a comma): aman,pap,lalu


OUTPUT


[4, 3, 4]



How to use Split() Method in python | Softcrayons IT Training Tutorial

No comments:

Post a Comment