Wouter van Epperzeel
Wouter van Epperzeel

Reputation: 21

Splitting a string every 2 digits

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.

Upvotes: 1

Views: 2352

Answers (2)

TheFaultInOurStars
TheFaultInOurStars

Reputation: 3608

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.

Edit

Based on your comment, you want to APPLY this on a column. In this case, you should do something like:

df["my_column"] = df["my_column"].apply(split_it)

Upvotes: 1

S.B
S.B

Reputation: 16496

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.

Upvotes: 1

Related Questions