Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a String when character is different to preceeding one in Python

I want to split a string taken from the user when the character at position K is different to K-1

I am having a some difficulties however.

Here is what I have so far:

UserInput = input("hi enter a string:")

Groups = []

for x in range(len(UserInput)):
    if (UserInput[x] != UserInput[x-1]):
        print(UserInput[x])

If you dont understand what I want here is an example: Say the user entered: b444Mrr--<<<]0 I want to output on the screen: b, 444, M, rr, --, <<<, ], 0

like image 884
user79868855 Avatar asked Mar 10 '26 22:03

user79868855


2 Answers

You could use itertools.groupby(), observe:

import itertools

user_input = input("Please enter a string:")
groups = []

for _, group in itertools.groupby(user_input):
  groups.append(''.join(group))

print('Here is that string split when a character changes: %s' % ', '.join(groups))

Example usage with given example:

Please enter a string: b444Mrr--<<<]0
Here is that string split when a character changes: b, 444, M, rr, --, <<<, ], 0

N.B. In Python use snake_case rather than TitleCase (what you are doing in your attempt) or camelCase

like image 97
Sash Sinha Avatar answered Mar 13 '26 12:03

Sash Sinha


you can use the logic that unicode value is different for each char and can be used for the comparison for different chars like below code:-

inp=input("Enter String ")

prev=ord(inp[0])
str1=inp[0]
str=inp[1:]
for i in str:
    curr=ord(i)
    if prev==curr:
        str1=str1+i
    elif prev!=curr:
        print(str1)
        prev=curr
        str1=""
        str1=i        
print(str1)

Example to demonstrate:-

Enter String b444Mrr--<<<]0
b 444 M rr -- <<< ] 0
like image 26
Neo Ravi Avatar answered Mar 13 '26 12:03

Neo Ravi