Introduction

The istr module makes it possible to use strings as if they were integers.

Changelog

For the changelog, see www.salabim.org/istr/changelog .

Background

Using strings as if they were integers can be very handy for solving puzzles, but also for other purposes. For instance, the famous send more money puzzle, where each letter has to be replaced by a unique digit (0-9)

can be nicely, albeit not very efficient, coded as:

or even

Of, if we want to add all the digits in a string:

The module is also a demonstration of extending a class (str) with additional and modified functionality.

Installation

Installing istr with pip is easy.

or when you want to upgrade,

Alternatively, istr.py can be just copied into your current work directory from GitHub (https://github.com/salabim/istr).

No dependencies!

Usage

Start

Just start with

or the more conventional, more verbose:

Use istr as int

We can define an istr, like:

The variables four and five can now be used as if they were int:

, after which twenty is istr('20')

The same can be done with

or

And now twenty can be used as if it was an int as well. So

is istr('16')

We can do all the usual arithmetic operations on istrs, e.g.

is istr('6')

And we can test for equality. So:

is True.

But istrs are actually strings! So

is also True!

For the order comparisons (<=, <, >, >=), an istr is always interpreted as an int.

That means that

are bothTrue.

In contrast to an ordinary string

prints 9, as istr are treated as ints (if possible).

Please note that four could have also been initialized with

or even

Important

All calculations are strictly integer calculations. That means that if a float or decimal variable is ever produced, it will be converted to an int. Also, divisions are always floor divisions!

Use istr as a string

We should realize that istrs are in fact strings.

To concatenate two istrs (or an istr and a str), we cannot use the + operator (remember four + five is istr('9')).

To concatenate strings, we use the or operator (|). So

will be istr(45`).

And

is istr('9').

To repeat a string in the usual sense, you cannot use the * operator (remember 3 * four is istr('12').

To repeat, we use the matrix multiplication operator (@). So

3 @ four

is istr('444')

And

four @ 3

is also istr('444')

Note

It is not allowed to use the @ operator for two istrs. So, four @ five raises a TypeError.

istr that can't be interpreted as an int

Although usually istrs are to be interpreted as an int, that's not a requirement.

So

or

are perfectly acceptable.

However, we cannot perform any arithmetic or comparison operations with them.

If we try

a TypeError will be raised.

That holds for any arithmetic we try.

If we want to test if an istr can be interpreted (and thus used in an arithmetic and comparison expression). we can use the is_int() method. So

ìstr(20).is_int()

is True, whereas

ìstr('abc').is_int()

is False.

 

The bool operator works normally on the integer value of an istr. So

bool(istr('0')) ==> False

bool(istr('1')) ==> True

But if the istr can't be interpreted as an int, the string value will be used to test. So

bool(istr('abc')) ==> True

bool(istr('')) ==> False

Other operators

For the in operator, an istr is treated as an ordinary string, although it is possible to use ints as well:

On the left hand side an istr is always treated as a string:

Sorting a list of istrs is based on the integer value, not the string. So

is

,whereas

is

Using values that are neither string nor numeric to initialize istr

Apart from with numeric (to be interpreted as an int) or str, istr can be initialized with several other types:

More than one parameter for istr

It is possible to give more than one parameter, in which case a tuple of the istrs of the parameters will be returned, which can be handy to unpack multiple values, e.g.

test for even/odd

It is possible to test for even/odd (provided the istr can be interpreted as an int) with the is_even and is_odd method, e.g.

It is also possible to test for even/odd of an ordinary int:

test for divisibility

It is possible to test whether an istr is divisible by a given value with the is_divisible_by method, e.g.

It is also possible to test for divisibility of an ordinary int:

The method divided_by not only tests divisibility, but also returns the result of the division. If not possible, None will be returned, unless the fallback (last argument) is given, in which case fallback will be returned.

test for square

It is possible to test whether the value is a perfect square (provided the istr can be interpreted as an int) with the is_square method, e.g.

It is also possible to test for square of an ordinary int:

test for cube

It is possible to test whether the value is a perfect cube (provided the istr can be interpreted as an int) with the is_cube method, e.g.

It is also possible to test for cube of an ordinary int:

test for power of

It is possible to test whether the value is a perfect power of a given exponent (provided the istr can be interpreted as an int) with the is_power_of method, e.g.

It is also possible to test for power of of an ordinary int:

test for prime

It is possible to test whether the value is a prime number (provided the istr can be interpreted as an int) with the is_prime method, e.g.

It is also possible to test for prime of an ordinary int:

test whether all characters are distinct

With the all_distinct method, it is possible to test whether all characters are distinct (i.e. no character appears more than once).

test if characters are consecutive

With the is_consecutive method, it is possible to test whether the individual digits (characters) are consecutive. ASCII-ordering is applied.

Note that this method can also be used for non-istr-s, like istr.is_consecutive(123) ==> True

test for triangular number

With the is_triangular method, it is possible to test whether this is a triangular number (sum of integers, starting at 1):

Note that this method can also be used for non-istr-s, like istr.is_triangular(6) ==> True.

reverse an istr

The method reversed() will return an istr with the reversed content:

The same can, of course, be achieved with

Note

It is possible to reverse a negative istr, but the result can't be interpreted as an int anymore.

enumerate with istrs

The istr.enumerate class method can be used just as the built-in enumerate function. The iteration counter however is an istr rather than an int. E.g.

prints

join with istrs

istr.join can be used just like str.join. The result will be an istr.

On top of that, istr.join may be used as a class method, like

itertools with istrs

All methods in itertools are also available directly from istr. Note that the result is istr-ed (apart from groupby and tee).

The following class methods are supported (provided their counterpart exists in the installed Python version's itertools):

This can be handy as these methods don't have to be imported from itertools anymore.

All methods have exactly the same (optional) parameters as their itertools counterpart.

For example:

One more example:

results in

concatenate an iterable

The istr.concat method can be useful to map all items of an iterable to istr and then concatenate these.

`

prod to get product of an iterable

The method prod can be used to return the product of an iterable (including an istr), like math.prod, but as istr. Thus, istr.prod(range(1,5)) is istr(24) And istr("123", start=4) is also istr(24).

It is also possible to apply prod on an istr: istr(1234).prod() is istr(24) istr("123").prod(start=4) is istr(24)

sumprod to get the sum of products of iterables

The class method istr.sumprod(), is equivalent to math.sumprod(), but applies istr to both iterables. Note that this method is available even in Python < 3.12 . Thus, istr.sumprod("12", (3,4)) is istr(11) In contrast to math.sumprod(), istr.sumprod() supports a strict parameter (True by default) Thus, istr.sumprod("12", (3,4,5), strict=False) is istr(11), whereas istr.sumprod("12", (3,4,5)) raises a ValueError.

get all squares, cubes, power ofs or primes in a given range

The class methods istr.squares, istr.cubes, istr.power_ofs and istr.primes can be used to get a list of all squares, cubes, power_ofs or primes up to a given upperbound (non inclusive) or between a given lower bound and upper bound (non inclusive), like:

istr.squares (100) returns a list of all squares <100 istr.squares(50, 100) returns a list of all squares in the range [50, 100)

Unless cache=False is specified, the query result is cached.

generate istr with digits

The class method digits can be used to return an istr of digits according to a given specification. The method takes either no or a number of arguments.

If no arguments are given, the result will be istr('0123456789').

The given argument(s) result in a range of digits.

(n and m must be digits between 0 and 9 or letters letters between A and Z)

When no stop value is specified, it will be

The final result is an istr composed of the given range(s).

Here are some examples:

Decomposing to and composing from letter variables

When we have an istr, we can decompose the value into individual one letter (global) variables with the decompose() method. E.g.

will set the global variables a, b and c to be set to istr(4). istr(8) andistr(5). Note that the length of the letters specifier must be the same as the length of the istr. Furthermore, multiple values for the same variables result in a ValueError.

To decompose an istr into individual variables, it is arguably easier and safer to unpack the istr, like

With istr.compose(), an istr can be constructed from individual (global) variables and digits. E.g.

Now, test1 will be istr(396) and test2 will be istr(3960).

Composing can also be done by prefixing a string with '=', like:

Note that str(istr("=")) is "=".

Composing and assignment can be done by prefixing a string with ':=', like:

Note that str(istr(":=")) is ":=" and does not assign any value.

Usually, composing and decomposing uses the globals namespace, but this can be overridden with the namespace parameter. See the test suite for details.

Subclassing istr

When a class is derived from istr, all methods will return that newly derived class.

E.g.

will print jstr('20')

Changing the way repr works

It is possible to control the way an istr instance will be repr'ed.

By default, istr(5) is represented as istr('5').

With the istr.repr_mode() context manager, that can be changed:

This will print

If the repr_mode is 'int' and the istr can't be interpreted as an int the string ? will be returned:

This will print

Note

The way an istr is represented is determined at initialization.

It is also possible to set the repr mode without a context manager:

This will print

Finally, the current repr mode can be queried with istr.repr_mode(). So upon start:

will output istr.

Changing the base system

By default, istr works in base 10. However it is possible to change the base system with the istr.base() context manager / method.

Any base between 2 and 36 may be used.

Note that the integer is always stored in base 10 mode, but the string representation will reflect the chosen base (at time of initialization).

Some examples:

This will result in

All calculations are done in the decimal 10 base system.

Note that the way an istr is interpreted is determined at initialization.

It is also possible to set the repr mode without a context manager:

This will print

Finally, the current base can be queried with istr.base(), so upon start:

will result in 10.

Changing the format of the string

When an istr is initialized with a string the istr will be always stored as such.

For initializing with an int (or other numeric) value, the string is by default simply the str representation

With the istr.int_format() context manager this behavior can be changed. If the format specifier is a number, most likely a single digit, that will be the minimum number of characters in the string:

will print

If the string starts with a 0, the string will be zero filled:

will print

Note

For bases other than 10, the string will never be reformatted!

Overview of operations

The table below indicates whether the string or integer version of istr is applied.

Test script

There's an extensive pytest script in the \tests directory.

This script also shows clearly the ways istr can be used, including several edge cases. Highly recommended to have a look at.

Contact info

You can contact Ruud van der Ham, the core developer, via ruud@salabim.org .

Badges

PyPI PyPI - Python Version PyPI - Implementation PyPI - License Black GitHub last commit