Home > database >  Splitting a string every 2 digits
Splitting a string every 2 digits

Time:04-07

I have a column existing of rows with different strings (Python). ex.

  1. 5456656352
  2. 435365
  3. 46765432 ...

I want to seperate the strings every 2 digits with a comma, so I have following result:

  1. 54,56,65,63,52
  2. 43,53,65
  3. 46,76,54,32 ...

Can someone help me please.

CodePudding user response:

Not sure about the structure of desired output (pandas and dataframes, pure strings, etc.). But, you can always use a regex pattern like:

import re
re.findall("\d{2}", "5456656352")

Output

['54', '56', '65', '63', '52']

You can have this output as a string too:

",".join(re.findall("\d{2}", "5456656352"))

Output

54,56,65,63,52

Explanation

\d{2} is a regex pattern that points to a part of a string that has 2 digits. Using findall function, this pattern will divide each string to elements containing just two digits.

CodePudding user response:

Try:

text = "5456656352"
print(",".join(text[i:i   2] for i in range(0, len(text), 2)))

output:

54,56,65,63,52

You can wrap it into a function if you want to apply it to a DF or ...

note: This will separate from left, so if the length is odd, there will be a single number at the end.

  • Related