Splitting a string from right at intervals in python

I’m trying to split a string from the right. Following is the code.

string = "abcde" 
n = len(string)
slices = [string[i-3:i] for i in range(n,0,-3)]
print (slices)

I get the output as ['cde', '']. I’m trying to get ['cde', 'ab']

But when I split it from left it gives the proper output, i.e..,

string = "abcde" 
slices = [string[i:i+3] for i in range(0,n,3)]
print (slices)

output: ['abc', 'de']

Can anyone point out where am I going wrong?

Solution:

You are close. You need to floor the first indexing argument at 0:

x = "abcde" 
n = len(x)
slices = [x[max(0,i-3):i] for i in range(n,0,-3)]

['cde', 'ab']

The reason your code does not work is because with positive indices, falling off the end means going as far as you can.

While negative indices means starting from the end, rather than going to the start and no further.

How to return String[][] after finish splitting a string twice?

Suppose I am splitting a String, I would like to split by char ‘E’ first then split them by ‘space’ again.

String str = "30 3 3 11 5 2 2 7 9 2 1 20 E 21 2 2 11 14 5 2 1 7 3 6 E 30 4 3 11 5 21 2 15 20 3 17 9 5 1 32 E" 

First split:

String[] first= str.split("E");

Second split:

for(int i=0; i<first.length; i++){
    String[] second = first[i].split(" ");
    return Second;
}

However this will only return the the string array at index 0. I would like to return the whole arrays.I tried to put the variable String[] Second outside of the loop. It does not work.

I would like the result to be the equivalent of:

String[][] result = {
        { "30", "3", "3" "11" "5" "2" "2" "7" "9" "2" "1" "20" },
        { "21", "2", "2" "11" "14" "5" "2" "1" "7" "3" "6" },
        { "30" "4" "3" "11" "5" "21" "2" "15" "20" "3" "17" "9" "5" "1" 32", "1", "32" }
};

Any suggestions ?

Solution:

If you want to split the string into an array of arrays of strings, then:

 String[] first= str.split("E");
 String[][] second = new String[first.length][];
 for (int i = 0; i < second.length; i++) {
     second[i] = first[i].split(" ");
 }

How to split the string inputted by user

This is for our assignment in Java Programming. I want to know how to split an inputted string by the user.
The program will ask the user to input his birth date in MM/dd format. After that I want the application to split the date (delimiter is the slash). Add the number. And output the zodiac sign base on the sum of the number.

Expected result :

Please enter your date of birth (MM/dd): 01/06
This is the mmdd value: 106
Result: Capricorn

But I am not getting this result with the following code:

public static void main(String[] args) {

    Scanner scan = new Scanner (System.in);
    int mmdd;
    int a;
    int b;

   System.out.print("Please enter your date of birth(MM/dd): ");
   String stringdate = scan.next();

   a = Integer.parseInt(stringdate.split("/") [0]);
   b = Integer.parseInt(stringdate.split("/") [1]);
   mmdd = a + b;

   System.out.println("This is the mmdd value: " + mmdd);

   System.out.print("Result: ");
     if (mmdd >= 321 && mmdd <= 419) {
         System.out.println("ARIES");
     } else if (mmdd >= 420 && mmdd <= 520) {
         System.out.println("TAURUS");
     } else if (mmdd >= 521 && mmdd <= 620) {
         System.out.println("GEMINI");
     } else if (mmdd >= 621 && mmdd <= 722) {
         System.out.println("CANCER");
     } else if (mmdd >= 723 && mmdd <= 822) {
         System.out.println("LEO");
     } else if (mmdd >= 823 && mmdd <= 922) {
         System.out.println("VIRGO");
     } else if (mmdd >= 923 && mmdd <= 1022) {
         System.out.println("LIBRA");
     } else if (mmdd >= 1023 && mmdd <= 1121) {
         System.out.println("SCORPIO");
     } else if (mmdd >= 1122 && mmdd <= 1221) {
         System.out.println("SAGITTARIUS");
     } else if ((mmdd >= 1222 && mmdd <= 1231) || (mmdd >= 11 && mmdd <= 119)) {
         System.out.println("CAPRICORN");
     } else if (mmdd >= 120 && mmdd <= 218) {
         System.out.println("AQUARIUS");
     } else if (mmdd >= 219 && mmdd <= 320) {
         System.out.println("PISCES");
     }
}

Solution:

a = Integer.parseInt(stringdate.split("/") [0]); gives you 1
b = Integer.parseInt(stringdate.split("/") [1]); gives you 6

So in fact you are summing 1 + 6 for that you get 7 and not 106.

Instead you can use :

String stringdate = scan.next();
stringdate = stringdate.replaceAll("[^\\d]+", "");//remove all non digits

mmdd = Integer.parseInt(stringdate);//then parse the result

If you enter 01/06 then mmdd return 106 and not 7

Split a string and save them to a list with Python

I have a string that I inserted a space into it in all different positions and saved them to a list. Now this list of strings with space in them, I want to split those strings and put the output in one list, when am doing this, it happens that am having multiple list inside:

This is the code am working on:

var ='sans'
res = [var[:i]+' '+var[i:] for i in range(len(var))]
// The previous line: AM adding a space to see maybe that would generate other words
cor = [res[i].split() for i in range (len(res))]

And this is the output am getting:

>>> cor
[['sans'], ['s', 'ans'], ['sa', 'ns'], ['san', 's']]

What am expecting:

>>> cor
    ['sans', 's', 'ans', 'sa', 'ns', 'san', 's']

Am new to python, I don’t know what am missing.

Thanks

Solution:

An alternative approach:

cor = " ".join(res).split()

Output:

['sans', 's', 'ans', 'sa', 'ns', 'san', 's']

Explanation

" ".join(res) will join the individual strings in res with a space in between them. Then calling .split() will split this string on whitespace back into a list.

EDIT: A second approach that doesn’t involve the intermediate variable res, although this one isn’t quite as easy on the eyes:

cor = [var[:i/2+1] if i%2==1 else var[i/2:] for i in range(2*len(var)-1)]

Basically you flip between building substrings from the front and the back.

terraform iterate over string

ingress = “22:192.168.0.0/24:tcp,80:172.16.120.0/16:tcp,8080:0.0.0.0/0:tcp”
egress = “22:192.168.0.0/24:tcp,80:172.16.120.0/16:tcp,8081:127.0.0.0/0:udp”

resource “openstack_compute_secgroup_v2” “secgroup_1” {
name = “secgroup”
description = “my security group”

count = “${length(split(“,”,var.ingress))}”
rule {
from_port = “${element(split(“:”,element(split(“,”,var.ingress),count.index)), 0)}”
to_port = “${element(split(“:”,element(split(“,”,var.ingress),count.index)), 0)}”
ip_protocol = “${element(split(“:”,element(split(“,”,var.ingress),count.index)), 2)}”
cidr = “${element(split(“:”,element(split(“,”,var.ingress),count.index)), 1)}”
}
}

Note: This will create multiple security groups if you want single security group and multiple rules use following code:

resource “openstack_networking_secgroup_v2” “secgroup” {
name = “secgroup”
description = “My neutron security group”
}

 

resource “openstack_networking_secgroup_rule_v2” “secgroup_rule_ingress” {

count = “${length(split(“,”,var.ingress))}”
direction = “ingress”
ethertype = “IPv4”
protocol = “${element(split(“:”,element(split(“,”,var.ingress),count.index)), 2)}”
port_range_min = “${element(split(“:”,element(split(“,”,var.ingress),count.index)), 0)}”
port_range_max = “${element(split(“:”,element(split(“,”,var.ingress),count.index)), 0)}”
remote_ip_prefix = “${element(split(“:”,element(split(“,”,var.ingress),count.index)), 1)}”
security_group_id = “${openstack_networking_secgroup_v2.secgroup_1.id}”
}

resource “openstack_networking_secgroup_rule_v2” “secgroup_rule_egress” {

count = “${length(split(“,”,var.egress))}”
direction = “egress”
ethertype = “IPv4”
protocol = “${element(split(“:”,element(split(“,”,var.egress),count.index)), 2)}”
port_range_min = “${element(split(“:”,element(split(“,”,var.egress),count.index)), 0)}”
port_range_max = “${element(split(“:”,element(split(“,”,var.egress),count.index)), 0)}”
remote_ip_prefix = “${element(split(“:”,element(split(“,”,var.egress),count.index)), 1)}”
security_group_id = “${openstack_networking_secgroup_v2.secgroup_1.id}”
}