简体   繁体   中英

Split numeric,strings,special characters in given string

Given a string S which consists of alphabets, numbers and special characters. You need to write a program to split the strings in three different strings S1, S2 and S3 such that the string S1 will contain all the alphabets present in S, the string S2 will contain all the numbers present in S and S3 will contain all special characters present in S. The strings S1, S2 and S3 should have characters in same order as they appear in input.

Input: First line of input contains a single integer T which denotes the number of test cases. First line of each test case contains a String S of alphabets, numbers and special characters. Output: For each test case, In the first line print the string S1 which contains all the alphabets of S. In the second line print the string S2 which contains all the numbers. In the third line print the string S3 which contains all the special characters present in S.

Constraints: 1<=T<=100 3<=Length(S)<=1000

Example: Input: 2 geeks01for02geeks03::! **Docoding123456789everyday## Output: geeksforgeeks 010203 !!! Docodingeveryday 123456789 **## my code :

enter code here
t=int(input())
a=[]
n=[]
st=[]
for _ in range(t):
    s=list(input())
    for i in s:
        if i.isalpha():
            a.append(i)
        
        elif i.isdigit():
            n.append(i)
        
        elif not i.isalnum():
            st.append(i)
    for i in a:
        print(i,end='')
    print('')    
    for i in n:
        print(i,end='')
    print('')    
    for i in s:
        print(i,end='')
    print('')   

my code is separating alphabets,numeric but not special Characters any one can tell me what is wrong in my python code

def splitString(str): 


    alpha = "" 
    num = "" 
    special = "" 
    for i in range(len(str)): 
        if (str[i].isdigit()): 
            num = num+ str[i] 
        elif((str[i] >= 'A' and str[i] <= 'Z') or
            (str[i] >= 'a' and str[i] <= 'z')): 
            alpha += str[i] 
        else: 
            special += str[i] 

    print(alpha) 
    print(num ) 
    print(special) 

t=int(input())
for i in range(t):
    s = input()
    splitString(s)

In your last for-loop to print the special characters, you are looping it over the wrong list. Change it to

for i in st:
   print(i)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM