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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With