Strings and bytes
Strings
In SmartPy strings are of type sp.string
. Characters are restricted to the printable subset of 7-bit ASCII.
String literals are written in quotes, e.g. "abc"
is a literal of type sp.string
.
Both strings and bytes can be concatenated with +
, e.g. "ab" + "c" == "abc"
.
- sp.slice(offset: sp.nat, length: sp.nat, s: sp.string) → sp.option[sp.string]
Extracts a substring from
s
, starting atoffset
(0
referring to the first character) and of lengthlength
. If the result is in bounds, the result will be wrapped insp.Some
, otherwiseNone
is returned.For example
sp.slice(3,5,"0123456789") == sp.Some("34567")
andsp.slice(3,5,"01234") == None
.
- sp.concat(xs: sp.list[sp.string]) → sp.string
sp.concat
concatenates a list of strings, for example:smartpyassert sp.concat(["ab","cd","ef"]) == "abcdef"
Bytes
The type sp.bytes
represents sequences of bytes.
Byte literals are written in hexadecimal notation: sp.bytes("0x100a")
refers to a two-byte sequence.
- sp.slice(offset: sp.nat, length: sp.nat, s: sp.bytes) → sp.option[sp.bytes]
Extracts a subsequence of bytes from
s
, starting atoffset
(0
referring to the first character) and of lengthlength
. If the result is in bounds, the result will be wrapped insp.Some
, otherwiseNone
is returned.For example
sp.slice(3,5,sp.bytes("0x00010203040506070809")) == sp.Some(sp.bytes("0x0304050607"))
andsp.slice(3,5,sp.bytes("0x0001020304")) == None
.
- sp.concat(xs: sp.list[sp.bytes]) → sp.bytes
sp.concat
concatenates a list ofsp.bytes
, for example:smartpyassert sp.concat([sp.bytes("0xab"), sp.bytes("0xcd")]) == sp.bytes("0xabcd")
Bitwise logic
As of the Mumbai protocol upgrade bitwise and, or and xor operations are available as sp.and_bytes
, sp.or_bytes
and sp.xor_bytes
on sp.bytes
:
- sp.xor_bytes(x: sp.bytes, y: sp.bytes) → sp.bytes
Performs the bitwise logical operations "and", "or", and "xor", respectively, on the arguments
x
andy
, for example:smartpyassert sp.and_bytes(sp.bytes("0x2a"), sp.bytes("0x01")) == sp.bytes("0x00") assert sp.or_bytes(sp.bytes("0x2a"), sp.bytes("0x01")) == sp.bytes("0x2b") assert sp.xor_bytes(sp.bytes("0x2a"), sp.bytes("0x01")) == sp.bytes("0x2b")
- sp.invert_bytes(x: sp.bytes) → sp.bytes
Computes the two's complement of
x
.
Shifting
Left and right shifts are also available as sp.lshift_bytes
and sp.rshift_bytes
on sp.bytes
:
- sp.lshift_bytes(x: sp.bytes, n: sp.nat) → sp.bytes
sp.lshift_bytes
shiftsx
to the left by a given amountn
, for example:smartpyassert sp.lshift_bytes(sp.bytes("0x2a"), sp.bytes("0x01")) == sp.bytes("0x54")
- sp.rshift_bytes(x: sp.bytes, n: sp.nat) → sp.bytes
sp.rshift_bytes
shiftsx
to the right by a given amountn
, for example:smartpyassert sp.rshift_bytes(sp.bytes("0x2a"), sp.bytes("0x01")) == sp.bytes("0x15")
Packing and unpacking
Most Michelson values can be packed and unpacked, i.e. converted to a sp.bytes
representation.