Split string by index python
I want to split a string by a list of indices, where the split segments begin with one index and end before the next one. Show Example:
This will return:
I'm trying to get:
smci 30.4k18 gold badges110 silver badges145 bronze badges asked Jun 1, 2012 at 13:43
returns
which you can print using:
Another possibility (without copying
answered Jun 1, 2012 at 13:45
eumiroeumiro 198k33 gold badges294 silver badges259 bronze badges 10 Here is a short solution with heavy usage of the itertools module. The
Edit: This is a version that does not copy the indices list, so it should be faster.
flywire 91110 silver badges31 bronze badges answered Jun 1, 2012 at 13:52
schlamarschlamar 9,0223 gold badges37 silver badges76 bronze badges 3 You can write a generator if you don't want to make any modifications to the list of indices:
answered Aug 3, 2019 at 22:18
Zhou ShaoZhou Shao 1161 silver badge4 bronze badges 0 Another solution (a bit more readable):
This reverses the indices and therefore starts splitting from the last index position to the 'endIndex' i2 (which is updated in every loop). Of course the elements are in the wrong order than. That's why I reversed the result array at the end. I think for beginners this is a bit more readable than the accepted answer. answered Jul 21 at 21:10
Can you divide a string in Python?String split is used to break the string into chunks. Python provides an in-built method called split() for string splitting. We can access the split string by using list or Arrays.
How do you split a string into substrings in Python?Python split() Method Syntax
When you need to split a string into substrings, you can use the split() method. In the above syntax:
How do I split a string in a specific position?To split a string at a specific index, use the slice method to get the two parts of the string, e.g. str. slice(0, index) returns the part of the string up to, but not including the provided index, and str. slice(index) returns the remainder of the string.
How do you split a string in Python with number of characters?Use range() and slicing syntax to split a string at every nth character. Use a for-loop and range(start, stop, step) to iterate over a range from start to stop where stop is the len(string) and step is every number of characters where the string will be split.
|