svs
svs

Reputation: 441

how to split a string in groups of multiple variables

I have a string

'abcdefgh12345678abcdefgh'

and i want to split it in 3 string of 8 variables:

'abcdefgh','12345678' and 'abcdefgh'

but i get a list of 3 strings:

['abcdefgh', '12345678', 'abcdefgh']

How can i do this?

Upvotes: 0

Views: 142

Answers (2)

Anders
Anders

Reputation: 8577

In Python, strings works sort of like arrays. You can access individual letters as elements in an array using brackets ([]). This means that your problem can be solved like this:

whole = 'abcdefgh12345678abcdefgh'
part1 = whole[0:8]    #abcdefgh
part2 = whole[8:16]   #12345678
part3 = whole[16:24]  #abcdefgh

Please note that if the string is shorter than 24 characters this will give you and index out of bounds error.

Or, if you want it directly in an array you can simply do it like this:

parts = [whole[0:8], whole[8:16], whole[16:24]]

But that is a bit repetitive. Lets find a better way to do it.

parts = [whole[i*8:(i+1)*8] for i in range(len(whole)//8)]

This will give you whole in 8 character long parts no matter how long it is, simply ignoring any extra parts at the end that does not fit into a full 8 character block. In the example of a 24 character string it would loop with i being equal to 0, 1 and 2 giving you exactly the same intervals as in the examples above.

Upvotes: 1

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

s = 'abcdefgh12345678abcdefgh'
import re

a, b, c = re.findall("\w{8}", s)
print(a, b, c)

a, b, c = (s[i:i + 8] for i in range(0, len(s), 8))
print(a, b, c)

Upvotes: 3

Related Questions