In a string, I want to just print one letter if it happens 2 times, i tried using itertools but if the letter is written 4 times it just prints one, and I need to print 2. Example:
input = rruunnnniinngg
output = running
Thanks btw.
With re.sub()
function (assuming only adjacent characters):
import re
s = 'rruunnnniinngg'
result = re.sub(r'(\S)\1', '\\1', s)
print(result)
The output:
running
(\\S)
- regex captured group containing a single non-whitespace character
\\1
- the value of the 1st captured group (the immediate previous character repeated)
You can try this:
from itertools import groupby
input1 = "rruunnnniinngg"
final_string = ''.join(map(lambda x: x[:(len(x)/2)], [''.join(list(b)) for a, b in groupby(input1)]))
Output:
'running'
it can be simply implemented using a while loop that :
-adds the current character in the output string
- checks weather the next character is same as current character.
-if yes, then it skips the next character by increasing the counter by an extra 1 unit.
def func(s):
i=0
p=''
while(i<len(s)-1):
p+=s[i]
if(s[i+1]==s[i]):
i+=1
i+=1
return p
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.