{ }codelper
substringsnested conditionsP0274

Imitating Python's a:b:c slicing

You are given a string s and q slicing queries.
For each query, print the string cut by the same rules as Python's s[a:b:c]. Let n be the length of s; character positions count from 0 at the front up to n − 1. A query has the form a:b or a:b:c.
Each of a, b and c is an integer or empty.
If c is missing or empty, the step c is 1. When c is positive: if a is empty, start is 0; if b is empty, stop is n. A given a gets n added if it is negative.
If the result is less than 0 it becomes 0, and if it is greater than n it becomes n; that is start.
b gives stop the same way. Then join the characters at positions start, start + c, start + 2c, … in order, while the position is less than stop. When c is negative: if a is empty, start is n − 1; if b is empty, stop is −1 (meaning character 0 is included). A given a gets n added if it is negative.
If the result is less than 0 it becomes −1, and if it is greater than n − 1 it becomes n − 1; that is start.
b gives stop the same way. Then join the characters at positions start, start + c, start + 2c, … in order, while the position is greater than stop. The first line gives s, the second line gives q, and the next q lines give one query each. For each query, print the cut string on one line.
If it is empty, print -.

Input
s is a string of 1 to 200 lowercase English letters and digits.
1 ≤ q ≤ 400.
When not empty, a, b and c are integers from -1,000 to 1,000, and c is not 0.
Queries contain no spaces
Output
q lines
Example 1 · stdin
codelper
8
1:4
:3
-3:
::-1
6:1:-2
5:2
::3
-100:100
stdout
ode
cod
per
repledoc
eld
-
cee
codelper
Example 2 · stdin
abcdef
8
::-1
3::-1
:2:-1
-1:-7:-1
-7::-1
10:0:-1
::-1000
1:-1:1000
stdout
fedcba
dcba
fed
fedcba
-
fedcb
f
b
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

Only Python takes both a step and negative positions with s[a:b:c].
An empty part is None, so passing s[slice(None, None, -1)] lets Python pick the defaults according to the sign of the step.
Other languages must build it: JS/TS slice(a, b) accepts negative positions but has no step (substring treats negatives as 0); Java substring(a, b), C# Substring(start, length) and Craykon Substring(start, count) throw when out of range.
C++ substr(pos, len) forgives only a too-long length; a pos past the end is out_of_range.
Trap ① with a negative step, an empty stop is −1, not 0.
Using 0 drops character 0 from ::-1.
That is also why filling the empty parts of s[a:b:c] with 0 or len(s) is wrong even in Python (s[0:8:-1] is empty).
② A negative position first gets n added and is clamped if still outside.
With a negative step, below 0 clamps to −1, not 0, so -100::-1 is empty.
③ With a negative step, the upper limit of start is n − 1, not n.
Allowing n reads outside the string (an error in Java, C# and Craykon, undefined behaviour in C).
④ Keep empty parts when splitting: Java split(":") drops trailing empty parts, so use split(":", -1).
C strtok also merges :: into one.
C++ std::optional and TS string | undefined can represent 'empty' separately from 0.

Pythonmain.py · 11 lines
import sys lines = sys.stdin.read().split("\n")s = lines[0].strip()q = int(lines[1])out = []for line in lines[2:2 + q]:    # 빈 칸은 None: s[None:None:-1]처럼 기본값을 Python이 정한다(0을 넣으면 안 된다)    parts = [int(p) if p else None for p in line.strip().split(":")]    out.append(s[slice(*parts)] or "-")print("\n".join(out))
JavaScriptmain.js · 29 lines
const lines = require("fs").readFileSync(0, "utf8").split("\n");const s = lines[0].trim();const n = s.length;const q = Number(lines[1]); // 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다function fit(x, lo, hi) {  if (x < 0) x += n;  return Math.min(Math.max(x, lo), hi);} function pySlice(text) {  const [a, b, c] = text.trim().split(":"); // c가 없으면 undefined  const step = c ? Number(c) : 1;  let out = "";  if (step > 0) {    const start = a ? fit(Number(a), 0, n) : 0;    const stop = b ? fit(Number(b), 0, n) : n;    for (let i = start; i < stop; i += step) out += s[i];  } else {    // 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다    const start = a ? fit(Number(a), -1, n - 1) : n - 1;    const stop = b ? fit(Number(b), -1, n - 1) : -1;    for (let i = start; i > stop; i += step) out += s[i];  }  return out || "-";} console.log(lines.slice(2, 2 + q).map(pySlice).join("\n"));
TypeScriptmain.ts · 31 lines
import { readFileSync } from "node:fs"; const lines: string[] = readFileSync(0, "utf8").split("\n");const s = lines[0].trim();const n = s.length;const q = Number(lines[1]); // 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다function fit(x: number, lo: number, hi: number): number {  if (x < 0) x += n;  return Math.min(Math.max(x, lo), hi);} function pySlice(text: string): string {  const [a, b, c]: (string | undefined)[] = text.trim().split(":"); // c가 없으면 undefined  const step = c ? Number(c) : 1;  let out = "";  if (step > 0) {    const start = a ? fit(Number(a), 0, n) : 0;    const stop = b ? fit(Number(b), 0, n) : n;    for (let i = start; i < stop; i += step) out += s[i];  } else {    // 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다    const start = a ? fit(Number(a), -1, n - 1) : n - 1;    const stop = b ? fit(Number(b), -1, n - 1) : -1;    for (let i = start; i > stop; i += step) out += s[i];  }  return out || "-";} console.log(lines.slice(2, 2 + q).map(pySlice).join("\n"));
JavaMain.java · 42 lines
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; public class Main {    static String s;    static int n;     // 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다    static int fit(int x, int lo, int hi) {        if (x < 0) x += n;        return Math.min(Math.max(x, lo), hi);    }     static String pySlice(String text) {        String[] p = text.split(":", -1); // -1: 끝의 빈 칸도 버리지 않는다        boolean hasA = !p[0].isEmpty(), hasB = !p[1].isEmpty();        int step = p.length == 3 && !p[2].isEmpty() ? Integer.parseInt(p[2]) : 1;        StringBuilder out = new StringBuilder();        if (step > 0) {            int start = hasA ? fit(Integer.parseInt(p[0]), 0, n) : 0;            int stop = hasB ? fit(Integer.parseInt(p[1]), 0, n) : n;            for (int i = start; i < stop; i += step) out.append(s.charAt(i));        } else {            // 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다            int start = hasA ? fit(Integer.parseInt(p[0]), -1, n - 1) : n - 1;            int stop = hasB ? fit(Integer.parseInt(p[1]), -1, n - 1) : -1;            for (int i = start; i > stop; i += step) out.append(s.charAt(i));        }        return out.length() > 0 ? out.toString() : "-";    }     public static void main(String[] args) throws IOException {        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        s = in.readLine().trim();        n = s.length();        int q = Integer.parseInt(in.readLine().trim());        StringBuilder out = new StringBuilder();        for (int t = 0; t < q; t++) out.append(pySlice(in.readLine().trim())).append('\n');        System.out.print(out);    }}
C#Main.cs · 47 lines
using System;using System.Text; class Program{    static string s = "";    static int n;     // 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다    static int Fit(int x, int lo, int hi)    {        if (x < 0) x += n;        return Math.Clamp(x, lo, hi);    }     static string PySlice(string text)    {        string[] p = text.Split(':'); // C#의 Split은 빈 칸도 남긴다        bool hasA = p[0] != "", hasB = p[1] != "";        int step = p.Length == 3 && p[2] != "" ? int.Parse(p[2]) : 1;        var sb = new StringBuilder();        if (step > 0)        {            int start = hasA ? Fit(int.Parse(p[0]), 0, n) : 0;            int stop = hasB ? Fit(int.Parse(p[1]), 0, n) : n;            for (int i = start; i < stop; i += step) sb.Append(s[i]);        }        else        {            // 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다            int start = hasA ? Fit(int.Parse(p[0]), -1, n - 1) : n - 1;            int stop = hasB ? Fit(int.Parse(p[1]), -1, n - 1) : -1;            for (int i = start; i > stop; i += step) sb.Append(s[i]);        }        return sb.Length > 0 ? sb.ToString() : "-";    }     static void Main()    {        s = Console.ReadLine().Trim();        n = s.Length;        int q = int.Parse(Console.ReadLine().Trim());        var output = new StringBuilder();        for (int t = 0; t < q; t++) output.Append(PySlice(Console.ReadLine().Trim())).Append('\n');        Console.Write(output);    }}
C++main.cpp · 53 lines
#include <algorithm>#include <iostream>#include <optional>#include <string>#include <vector> std::string s;int n; // 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다int fit(int x, int lo, int hi) {    if (x < 0) x += n;    return std::clamp(x, lo, hi);} std::string pySlice(const std::string &text) {    std::vector<std::optional<int>> p; // 빈 칸은 값이 없는 optional    std::size_t from = 0;    while (true) {        std::size_t colon = text.find(':', from);        std::string part = text.substr(from, colon == std::string::npos ? std::string::npos : colon - from);        p.push_back(part.empty() ? std::nullopt : std::optional<int>(std::stoi(part)));        if (colon == std::string::npos) break;        from = colon + 1;    }    int step = p.size() == 3 && p[2] ? *p[2] : 1;    std::string out;    if (step > 0) {        int start = p[0] ? fit(*p[0], 0, n) : 0;        int stop = p[1] ? fit(*p[1], 0, n) : n;        for (int i = start; i < stop; i += step) out += s[i];    } else {        // 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다        int start = p[0] ? fit(*p[0], -1, n - 1) : n - 1;        int stop = p[1] ? fit(*p[1], -1, n - 1) : -1;        for (int i = start; i > stop; i += step) out += s[i];    }    return out.empty() ? "-" : out;} int main() {    int q;    std::cin >> s >> q;    n = static_cast<int>(s.size());    std::string out;    for (int t = 0; t < q; t++) {        std::string line;        std::cin >> line;        out += pySlice(line) + '\n';    }    std::cout << out;    return 0;}
Cmain.c · 47 lines
#include <stdio.h>#include <stdlib.h>#include <string.h> static char s[256];static int n; /* 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다 */static int fit(int x, int lo, int hi) {    if (x < 0) x += n;    return x < lo ? lo : x > hi ? hi : x;} int main(void) {    char line[64];    int q;    scanf("%255s %d", s, &q);    n = (int)strlen(s);    for (int t = 0; t < q; t++) {        scanf("%63s", line);        /* ':'로 칸을 나눈다. strtok는 빈 칸을 건너뛰어서 직접 나눈다 */        char *part[3] = {line, NULL, NULL};        int k = 1;        for (char *c = line; *c; c++)            if (*c == ':') {                *c = '\0';                part[k++] = c + 1;            }        int hasA = part[0][0] != '\0', hasB = part[1][0] != '\0';        int step = k == 3 && part[2][0] != '\0' ? atoi(part[2]) : 1;        char out[256];        int len = 0;        if (step > 0) {            int start = hasA ? fit(atoi(part[0]), 0, n) : 0;            int stop = hasB ? fit(atoi(part[1]), 0, n) : n;            for (int i = start; i < stop; i += step) out[len++] = s[i];        } else {            /* 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다 */            int start = hasA ? fit(atoi(part[0]), -1, n - 1) : n - 1;            int stop = hasB ? fit(atoi(part[1]), -1, n - 1) : -1;            for (int i = start; i > stop; i += step) out[len++] = s[i];        }        out[len] = '\0';        puts(len > 0 ? out : "-");    }    return 0;}
Craykonmain.cray · 64 lines
s = Console.ReadLine().Trim();n = s.Length;q = Console.ReadLine().ToNumber(); // 음수 자리는 n을 더하고, 그래도 밖이면 [lo, hi] 안으로 당긴다맞추기(x, lo, hi){    if (x < 0)    {        x = x + n;    }    return Mathf.Min(Mathf.Max(x, lo), hi);} for (t = 0; t < q; t++){    p = Console.ReadLine().Trim().Split(":");    걸음 = 1;    if (p.Count == 3 && p[2] != "")    {        걸음 = p[2].ToNumber();    }    답 = "";    if (걸음 > 0)    {        시작 = 0;        끝 = n;        if (p[0] != "")        {            시작 = 맞추기(p[0].ToNumber(), 0, n);        }        if (p[1] != "")        {            끝 = 맞추기(p[1].ToNumber(), 0, n);        }        for (k = 시작; k < 끝; k = k + 걸음)        {            답 = 답 + s[k];        }    }    else    {        // 거꾸로 갈 때 빈 끝은 0번 글자까지 넣는다는 뜻이라 -1로 둔다        시작 = n - 1;        끝 = -1;        if (p[0] != "")        {            시작 = 맞추기(p[0].ToNumber(), -1, n - 1);        }        if (p[1] != "")        {            끝 = 맞추기(p[1].ToNumber(), -1, n - 1);        }        for (k = 시작; k > 끝; k = k + 걸음)        {            답 = 답 + s[k];        }    }    if (답 == "")    {        답 = "-";    }    Console.WriteLine(답);}