-8

I need to split a string by using repeated characters.

For example:

My string is "howhowhow"

I need output as 'how,how,how'.

I cant use 'how' directly in my reg exp. because my input varies. I should check the string whether it is repeating the character and need to split that characters.

cdlane
  • 40,441
  • 5
  • 32
  • 81
Kavi
  • 11
  • 1

2 Answers2

2
import re

string = "howhowhow"

print(','.join(re.findall(re.search(r"(.+?)\1", string).group(1), string)))

OUTPUT

howhowhow -> how,how,how
howhowhowhow -> how,how,how,how
testhowhowhow -> how,how,how  # not clearly defined by OP

The pattern is non-greedy so that howhowhowhow doesn't map to howhow,howhow which is also legitimate. Remove the ? if you prefer the longest match.

cdlane
  • 40,441
  • 5
  • 32
  • 81
0
lengthofRepeatedChar = 3
str1 = 'howhowhow'
HowmanyTimesRepeated = int(len(str1)/lengthofRepeatedChar)
((str1[:lengthofRepeatedChar]+',')*HowmanyTimesRepeated)[:-1]
'how,how,how'

Works When u know the length of repeated characters

Shivpe_R
  • 1,022
  • 2
  • 20
  • 31