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 at offset
(0
referring to the first character) and of length length
. If the result is in bounds, the result will be wrapped in sp.Some
, otherwise None
is returned.
For example sp.slice(3,5,"0123456789") == sp.Some("34567")
and sp.slice(3,5,"01234") == None
.
sp.concat(xs: sp.list[sp.string]) -> sp.string
sp.concat
concatenates a list of strings, for example:
assert 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 at offset
(0
referring to the first character) and of length length
. If the result is in bounds, the result will be wrapped in sp.Some
, otherwise None
is returned.
For example sp.slice(3,5,sp.bytes("0x00010203040506070809")) == sp.Some(sp.bytes("0x0304050607"))
and sp.slice(3,5,sp.bytes("0x0001020304")) == None
.
sp.concat(xs: sp.list[sp.bytes]) -> sp.bytes
sp.concat
concatenates a list of sp.bytes
, for example:
assert sp.concat([sp.bytes("0xab"), sp.bytes("0xcd")]) == sp.bytes("0xabcd")
Packing and unpacking
Most Michelson values can be packed and unpacked, i.e. converted to a sp.bytes
representation.
sp.pack(x: t) : sp.bytes
Packs a value, i.e. obtains its sp.bytes
representation.
The type t
must be packable, which means that it doesn't involve big maps, operations, sapling states, or tickets.
sp.unpack(x: sp.bytes, t) -> sp.option[t]
Unpacks the sp.bytes
representation x
, assuming it represents a value of type t
. Returns None
if x
does not represent a value of type t
.