Home > Mobile >  Separating strings based on user-input python
Separating strings based on user-input python

Time:12-29

I posted this earlier today and I got my answer but I wanna try something else in case of any changes that I possibly I make to my script so if this got a solution I would be grateful.

You can view the original code by this link to my other question but here is a quick look at it, it won't cover the whole thing but here it is:

import re
string = "RV49CJ0AUTS172Y"

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

print(separated)

So I have this:

2 = 14
3 = 12-15-18-21
4 = 12-16
5 = 10-5

This is what I need for the separation part, the numbers on the left are the number of parts that I want the string to be separated too, and the numbers on the right are the lengths that the user may input and based on the input of the user the string should be separated according to where the number goes back to. For example, if the user chose 18 as length then the string should be separated into 3 parts if the user chooses 16 then the string will be separated into 4 parts, and so on.

Char_18 = AS0MN5R1V85HN10OLA
separated = AS0MN5-R1V85H-N10OLA

Char_16 = NAH9186GMZLO1P09
separated = NAH9-186G-MZLO-1P09

So how do I apply this to my script? Any help would be great!

CodePudding user response:

I found the answer if anyone wants it in the future so here it is:

import re
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
all = chars   numbers
while True:
    length = int(input("Select the length you want for your key: "))
    if 5 <= length <= 21:
        break
length_1 = 0
div_2 = 14
div_3 = 12,15,18,21
div_4 = 16,20
div_5 = 10,5
if length % div_2 == 0:
    length_1 = 2
elif any(length % i == 0 for i in div_3):        
    length_1 = 3
elif any(length % i == 0 for i in div_4):
    length_1 = 4
elif any(length % i == 0 for i in div_5):
    length_1 = 5
key = "".join(random.sample(all, length))
length_2 = int(len(key) / length_1)
separated = "-".join(re.findall('.{%d}' % length_2, key)

This is part of my code I couldn't post a direct answer because if anyone tries to use it they will be so confused but the main part that can answer your question is this:

while True:
    length = int(input("Select the length you want for your key: "))
    if 5 <= length <= 21:
        break
length_1 = 0
div_2 = 14
div_3 = 12,15,18,21
div_4 = 16,20
div_5 = 10,5
if length % div_2 == 0:
    length_1 = 2
elif any(length % i == 0 for i in div_3):        
    length_1 = 3
elif any(length % i == 0 for i in div_4):
    length_1 = 4
elif any(length % i == 0 for i in div_5):
    length_1 = 5

and this:

length_2 = int(len(key) / length_1)
separated = "-".join(re.findall('.{%d}' % length_2, key)

I hope this will be helpful for anyone who has the same question.

  • Related