How do i format string with comma delimited

371 views Asked by At

please find the image I have a string like this : Hello,1,2 World,6,7 Home,10,11 I want my output as : Hello World Home 1 6 10 2 7 11 Below is my code: def a = "Hello,1,2 World,6,7 Home,10,11"; a=a.replace(',',"\n") println(a)

3

There are 3 answers

0
user426 On

You can simply do string.split(',') to get a list , and ' '.join(string.split(',')) to get a string of all these elements separated by a ' '. This is very simple splitting, for more sophisticated parsing, use the csv module.

This answer is for Python. I don't know why you have both java and python as tags.

2
AudioBubble On

You cannot generate that output logically as there is no (obvious) way to determine the order of the integers.

However, if you just want to isolate the words and integers then join them together in the order in which they were defined, then that can be done.

The tokens in your initial string are not just comma separated so the split technique suggested in previous answers won't work. You'll need to use the regex module thus:

import re

d = 'Hello,1,2 World,6,7 Home,10,11'
w = ''
n = ''
for token in re.split(',| ', d):
    try:
        int(token)
        n += token + ' '
    except ValueError:
        w += token + ' '

print(w + n.rstrip())

The output of this will be: Hello World Home 1 2 6 7 10 11

0
Hina Halani On
public static void main(String[] args) {
    String a = "Hello,1,2 World,6,7 Home,10,11";
    
    StringBuffer sb1 = new StringBuffer();
    StringBuffer sb2 = new StringBuffer();
    StringBuffer sb3 = new StringBuffer();
    String[] ar = a.split(",");
    for (int i = 0; i < ar.length; i++) {
        if(ar[i].contains(" ") && isNumeric(ar[i].split(" ")[0])){
            sb1.append(ar[i].split(" ")[0]+" ");
            sb2.append(ar[i].split(" ")[1]+" ");
        } else if(isNumeric(ar[i])){
            sb3.append(ar[i]+" ");
        } else{
            sb2.append(ar[i]+" ");
        }
    }
    System.out.println(sb2+""+sb3+""+sb1);
}

public static boolean isNumeric(String strNum) {
    if (strNum == null) {
        return false;
    }
    try {
        double i = Integer.parseInt(strNum);
    } catch (NumberFormatException nfe) {
        return false;
    }
    return true;
}

you should try this.