I have a column existing of rows with different strings (Python). ex.
- 5456656352
- 435365
- 46765432 ...
I want to seperate the strings every 2 digits with a comma, so I have following result:
- 54,56,65,63,52
- 43,53,65
- 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.