+ 2
What is split function used for?
6 Réponses
+ 6
Shreya ,
let me give you an example with this task description:
▪︎take a sentence as input and calculate the average word lenght
in this case a sentence is used like:
song = "this is major tom to ground control"
to do this task, you need to:
▪︎ separate the words to individual strings and put them to a list for further processing
▪︎ to do so split() is used. in case of a space should be used to separate, no argument is needed: words = song.split()
▪︎ the result will be : ['this', 'is', 'major', 'tom', 'to', 'ground', 'control']
▪︎now further processing can be done: iterate through list and count the characters of each word and calculate a running sum for total number of characters. finally use the total number of characters and divide it by the number of words
happy coding!
+ 7
To be accurate, you should probably call split() a method, rather than a function. Methods are called on objects, in this case the string, and the object and the method are connected by a dot.
There are many built-in string methods but only a few built-in function that work with strings, e.g. len().
Here are all the string methods
https://code.sololearn.com/clzf6rNcraj8
+ 4
it returns a list, using split's argument as the point to "split" the string, wherever the character or characters are in the string.
a = "mississippi"
b = a.split('i')
c = a.split("si")
print(b)
print(c)
# output
["m", "ss", "ss", "pp"]
["mis", "s", "ppi"]
+ 4
You can check this examples:
https://code.sololearn.com/cWQe70TuCAW2/?ref=app
https://code.sololearn.com/cT5Iz3KZ4TG5/?ref=app
https://code.sololearn.com/cDaOAxzq97Wz/?ref=app
https://code.sololearn.com/cYZcScNJkAhl/?ref=app
https://code.sololearn.com/chCw1Mrd2uQK/?ref=app
https://code.sololearn.com/cmWsD5S2Y278/?ref=app
+ 4
I can't explain in such good manner but according to me as I have used it so much in that,
It is used mostly in handling multiple inputs in one line in my case,
Usually we get many integer inputs with spaces in coding websites, so to replace
cin<<X<<" "<<... N times //C++
We use list comprehension
[int(i) for i in input.split()]
+ 4
Thank You all