Reputation: 21
I have a column existing of rows with different strings (Python). ex.
I want to seperate the strings every 2 digits with a comma, so I have following result:
Can someone help me please.
Upvotes: 1
Views: 2352
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")
['54', '56', '65', '63', '52']
You can have this output as a string too:
",".join(re.findall("\d{2}", "5456656352"))
54,56,65,63,52
\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.
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
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