Recent Changes - Search:

Oktatás

* Programozás 1
  + feladatsor
  + GitHub oldal

* Szkriptnyelvek
  + feladatsor
  + quick link

Teaching

Programming 1 (BI)
  ▸ exercises
  ▸ quick link

teaching assets


Félévek

* 2025/26/2
* archívum


Linkek

* kalendárium
* tételsorok
* jegyzetek
* szakdolgozat / PhD
* ösztöndíjak
* certificates
* C lang.
* C#
* D lang.
* Java
* Nim
* Nim2
  + exercises
* XC=BASIC
* old
  ✦C++, ✦Clojure, ✦Scala


[ edit | logout ]
[ sandbox | passwd ]

removePrefix, removeSuffix

See also std/strutils

Python also has these two string methods. However, in Python, they return a new string object. In Nim, they modify the string in-place. If you want a Python-like behaviour, you can do that with a custom function.

removePrefix()

removePrefix()
s = "https://python.org"

print(s.removeprefix("https://"))  # python.org

print(s.removeprefix("ftp://"))  # https://python.org
import std/strutils

var s = "https://python.org"  # var, can be modified

s.removePrefix("https://")  # change in-place

echo s  # python.org ; `s` has changed!

# ---

func withoutPrefix*(s, prefix: string): string =
  ## Remove the given prefix. Returns a new string.
  result = s
  result.removePrefix(prefix)

let url  = "https://python.org"  # let, immutable

echo url.withoutPrefix("https://")  # python.org

echo url  # https://python.org ; original string

removeSuffix()

Can be done similarly to removePrefix() .

Using dup from std/sugar

See dup in std/sugar

I learned later about the dup macro, which "turns an in-place algorithm into one that works on a copy and returns this copy, without modifying its input. This macro also allows for (otherwise in-place) function chaining."

My only problem is the strange syntax when using dup:

import std/strutils
import std/sugar      # dup

let
  url  = "https://python.org"  # let, immutable
  url2 = url.dup               # makes a copy
  # ---
  naked1 = url.dup(removePrefix("https://"))  # python.org
  naked2 = url.dup removePrefix("https://")   # python.org
  naked3 = dup url: removePrefix("https://")  # python.org
  naked4 = url.dup: removePrefix("https://")  # python.org

echo url      # https://python.org
echo url2     # https://python.org

echo naked1   # python.org
echo naked2   # python.org
echo naked3   # python.org
echo naked4   # python.org

Maybe naked3 and naked4 have the best syntax. naked1 and naked2 are weird for me.

Cloud City

  

Blogjaim, hobbi projektjeim

* The Ubuntu Incident
* Python Adventures
* @GitHub
* heroku
* extra
* haladó Python
* YouTube listák


Debrecen | la France


[ edit ]

Edit - History - Print *** Report - Recent Changes - Search
Page last modified on 2026 June 04, 15:03