Home > OS >  Is there a way of splitting a word into equal parts in python?
Is there a way of splitting a word into equal parts in python?

Time:12-26

I asked this question a few weeks ago and I got an answer this is the original post

But I need the output to be separated into equal parts whatever the length of the string is so in the first post I made I had this answer and it worked great as I needed thanks to (AziMez) he gave me the code and worked great

Code:

import re
string = "RV49CJ0AUTS172Y"

separated = "-".join(re.findall('.{%d}' % 5, string))

print(separated)

and I had this output which is what I wanted at the time:

RV49C-J0AUT-S172Y

But now I made the thing user based so the user inputs a length to the string and it separates the string into equal parts like if I had this input:

RV49CJ0AUTS172Y

I get this output:

RV49C-J0AUT-S172Y

and this is what I had gotten originally but I don't work on all lengths For example This is a 12 character string:

char = B1NS8XMA0LO5

I want to get this output:

separated = B1NS-8XMA-0LO5

I can always change the number to 4 in the original code like this:

separated = "-".join(re.findall('.{%d}' % 4, string))

But I can't keep it this way because the user input will vary from time to time and I want this to be done based on the user input I want the char to be separated into equal parts which are separated by a hyphen(Like how I did in the output part) Thanks

CodePudding user response:

length = int(len(string) / 3)
separated = "-".join(re.findall('.{%d}' % length, string))
  • Related