2017-09-13 39 views
3

前述一個不同的字符串我想要分割從用戶拍攝的字符串時,位置k處的字符是不同的,以K-1拆分時字符是在Python

我有一個卻有些困難。

這是我到目前爲止有:

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

Groups = [] 

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

如果你不明白我想這裏有一個例子: 假設用戶輸入:b444Mrr-- < < <] 0 我要輸出在屏幕上:b,444,男,RR, - ,< < <,],0

回答

3

你可以使用itertools.groupby(),觀察:

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)) 

實施例使用與給定的例子:

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

N.B.在Python中使用snake_case而不是TitleCase(你的嘗試在做什麼)或camelCase

+1

哇,這是偉大的 – user79868855

1

您可以使用Unicode值是每個字符的不同,可以用於不同的字符如下面的代碼進行比較的邏輯: -

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) 

例子來說明: -

Enter String b444Mrr--<<<]0 
b 444 M rr -- <<< ] 0