cardinal_pythonlib.stringfunc


Original code copyright (C) 2009-2022 Rudolf Cardinal (rudolf@pobox.com).

This file is part of cardinal_pythonlib.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.


cardinal_pythonlib.stringfunc.find_nth(s: str, x: str, n: int = 0, overlap: bool = False) int[source]

Finds the position of nth occurrence of x in s, or -1 if there isn’t one.

  • The n parameter is zero-based (i.e. 0 for the first, 1 for the second…).

  • If overlap is true, allows fragments to overlap. If not, they must be distinct.

As per https://stackoverflow.com/questions/1883980/find-the-nth-occurrence-of-substring-in-a-string

cardinal_pythonlib.stringfunc.mangle_unicode_to_ascii(s: Any) str[source]

Mangle unicode to ASCII, losing accents etc. in the process.

cardinal_pythonlib.stringfunc.multiple_replace(text: str, rep: Dict[str, str]) str[source]

Returns a version of text in which the keys of rep (a dict) have been replaced by their values.

As per https://stackoverflow.com/questions/6116978/python-replace-multiple-strings.

cardinal_pythonlib.stringfunc.replace_in_list(stringlist: Iterable[str], replacedict: Dict[str, str]) List[str][source]

Returns a list produced by applying multiple_replace() to every string in stringlist.

Parameters:
  • stringlist – list of source strings

  • replacedict – dictionary mapping “original” to “replacement” strings

Returns:

list of final strings

cardinal_pythonlib.stringfunc.split_string(x: str, n: int) List[str][source]

Split string into chunks of length n

cardinal_pythonlib.stringfunc.strnum(prefix: str, num: int, suffix: str = '') str[source]

Makes a string of the format <prefix><number><suffix>.

cardinal_pythonlib.stringfunc.strnumlist(prefix: str, numbers: List[int], suffix: str = '') List[str][source]

Makes a string of the format <prefix><number><suffix> for every number in numbers, and returns them as a list.

cardinal_pythonlib.stringfunc.strseq(prefix: str, first: int, last: int, suffix: str = '') List[str][source]

Makes a string of the format <prefix><number><suffix> for every number from first to last inclusive, and returns them as a list.