Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Split String of Size N in Python
Suppose we have a string s and an integer n, we have to split the s into n-sized pieces.
So, if the input is like s = "abcdefghijklmn", n = 4, then the output will be ['abcd', 'efgh', 'ijkl', 'mn']
To solve this, we will follow these steps −
- i:= 0
- f:= a new list
- while i < size of s, do
- insert s[from index i to i+n-1] at the end of f
- i := i + n
- return f
Let us see the following implementation to get better understanding −
Example
class Solution:
def solve(self, s, n):
i=0
f=[]
while(i<len(s)):
f.append(s[i:i+n])
i+=n
return(f)
ob = Solution()
print(ob.solve("abcdefghijklmn", 4))
Input
"abcdefghijklmn", 4
Output
['abcd', 'efgh', 'ijkl', 'mn']
Advertisements