Mojo struct
String
struct String
Represents a mutable string.
Aliases
ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"
:ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
:ASCII_LETTERS = "abcdefghijklmnopqrstuvwxyz".__add__[__mlir_type.!kgen.string]("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
:DIGITS = "0123456789"
:HEX_DIGITS = "0123456789".__add__[__mlir_type.!kgen.string]("abcdef").__add__[__mlir_type.!kgen.string]("ABCDEF")
:OCT_DIGITS = "01234567"
:PUNCTUATION = "!\22#$%&'()*+,-./:;<=>?@[\\]^_
{|}~"`:PRINTABLE = "0123456789".__add__[__mlir_type.!kgen.string]("abcdefghijklmnopqrstuvwxyz".__add__[__mlir_type.!kgen.string]("ABCDEFGHIJKLMNOPQRSTUVWXYZ")).__add__[__mlir_type.!kgen.string]("!\22#$%&'()*+,-./:;<=>?@[\\]^_
{|}~").add[__mlir_type.!kgen.string](" \t\n\r\v\f")`:
Implemented traits
AnyType
,
Boolable
,
CollectionElementNew
,
Comparable
,
Copyable
,
EqualityComparable
,
ExplicitlyCopyable
,
FloatableRaising
,
GreaterThanComparable
,
GreaterThanOrEqualComparable
,
Hashable
,
IntableRaising
,
KeyElement
,
LessThanComparable
,
LessThanOrEqualComparable
,
Movable
,
PathLike
,
PythonConvertible
,
Representable
,
Sized
,
Stringable
,
UnknownDestructibility
,
Writable
,
WritableCollectionElement
,
Writer
,
_HashableWithHasher
Methods
__init__
__init__(out self)
Construct an empty string.
__init__(out self, *, capacity: Int)
Construct an empty string with a given capacity.
Args:
- capacity (
Int
): The capacity of the string to allocate.
@implicit
__init__(out self, data: StringSlice[StaticConstantOrigin])
Construct a string from a static constant string without allocating.
Args:
- data (
StringSlice[StaticConstantOrigin]
): The static constant string to refer to.
@implicit
__init__(out self, data: StringLiteral[value])
Construct a string from a string literal without allocating.
Args:
- data (
StringLiteral[value]
): The static constant string to refer to.
__init__(out self, bytes: Span[SIMD[uint8, 1], origin])
Construct a string by copying the data. This constructor is explicit because it can involve memory allocation.
Args:
- bytes (
Span[SIMD[uint8, 1], origin]
): The bytes to copy.
__init__[T: Stringable](out self, value: T)
Initialize from a type conforming to Stringable
.
Parameters:
- T (
Stringable
): The type conforming to Stringable.
Args:
- value (
T
): The object to get the string representation of.
__init__[T: StringableRaising](out self, value: T)
Initialize from a type conforming to StringableRaising
.
Parameters:
- T (
StringableRaising
): The type conforming to Stringable.
Args:
- value (
T
): The object to get the string representation of.
Raises:
If there is an error when computing the string representation of the type.
__init__[*Ts: Writable](out self, *args: *Ts, *, sep: StringSlice[StaticConstantOrigin] = __init__[__mlir_type.!kgen.string](""), end: StringSlice[StaticConstantOrigin] = __init__[__mlir_type.!kgen.string](""))
Construct a string by concatenating a sequence of Writable arguments.
Examples:
Construct a String from several Writable
arguments:
var string = String(1, 2.0, "three", sep=", ")
print(string) # "1, 2.0, three"
var string = String(1, 2.0, "three", sep=", ")
print(string) # "1, 2.0, three"
.
Parameters:
- *Ts (
Writable
): The types of the arguments to format. Each type must be satisfyWritable
.
Args:
- *args (
*Ts
): A sequence of Writable arguments. - sep (
StringSlice[StaticConstantOrigin]
): The separator used between elements. - end (
StringSlice[StaticConstantOrigin]
): The String to write after printing the elements.
__init__[*Ts: Writable](out self, args: VariadicPack[is_owned, origin, Writable, Ts], sep: StringSlice[StaticConstantOrigin] = __init__[__mlir_type.!kgen.string](""), end: StringSlice[StaticConstantOrigin] = __init__[__mlir_type.!kgen.string](""))
Construct a string by passing a variadic pack.
Examples:
fn variadic_pack_to_string[
*Ts: Writable,
](*args: *Ts) -> String:
return String(args)
string = variadic_pack_to_string(1, ", ", 2.0, ", ", "three")
fn variadic_pack_to_string[
*Ts: Writable,
](*args: *Ts) -> String:
return String(args)
string = variadic_pack_to_string(1, ", ", 2.0, ", ", "three")
.
Parameters:
- *Ts (
Writable
): The types of the arguments to format. Each type must be satisfyWritable
.
Args:
- args (
VariadicPack[is_owned, origin, Writable, Ts]
): A VariadicPack of Writable arguments. - sep (
StringSlice[StaticConstantOrigin]
): The separator used between elements. - end (
StringSlice[StaticConstantOrigin]
): The String to write after printing the elements.
__init__(out self, *, unsafe_uninit_length: UInt)
Construct a String with the specified length, with uninitialized memory. This is unsafe, as it relies on the caller initializing the elements with unsafe operations, not assigning over the uninitialized data.
Args:
- unsafe_uninit_length (
UInt
): The number of bytes to allocate.
__init__(out self, *, unsafe_from_utf8_ptr: UnsafePointer[SIMD[int8, 1], mut=mut, origin=origin])
Creates a string from a UTF-8 encoded nul-terminated pointer.
Safety:
unsafe_from_utf8_ptr
MUST be valid UTF-8 encoded data.unsafe_from_utf8_ptr
MUST be null terminated.
Args:
- unsafe_from_utf8_ptr (
UnsafePointer[SIMD[int8, 1], mut=mut, origin=origin]
): AnUnsafePointer[Byte]
of null-terminated bytes encoded in UTF-8.
__init__(out self, *, unsafe_from_utf8_ptr: UnsafePointer[SIMD[uint8, 1], mut=mut, origin=origin])
Creates a string from a UTF-8 encoded nul-terminated pointer.
Safety:
unsafe_from_utf8_ptr
MUST be valid UTF-8 encoded data.unsafe_from_utf8_ptr
MUST be null terminated.
Args:
- unsafe_from_utf8_ptr (
UnsafePointer[SIMD[uint8, 1], mut=mut, origin=origin]
): AnUnsafePointer[Byte]
of null-terminated bytes encoded in UTF-8.
__copyinit__
__copyinit__(out self, other: Self)
Copy initialize the string from another string.
Args:
- other (
Self
): The string to copy.
__moveinit__
__moveinit__(out self, owned other: Self)
Move initialize the string from another string.
Args:
- other (
Self
): The string to move.
__del__
__del__(owned self)
Destroy the string data.
__bool__
__bool__(self) -> Bool
Checks if the string is not empty.
Returns:
True if the string length is greater than zero, and False otherwise.
__getitem__
__getitem__[I: Index](self, idx: I) -> Self
Gets the character at the specified position.
Parameters:
- I (
Index
): A type that can be used as an index.
Args:
- idx (
I
): The index value.
Returns:
A new string containing the character at the specified position.
__getitem__(self, span: Slice) -> Self
Gets the sequence of characters at the specified positions.
Args:
- span (
Slice
): A slice that specifies positions of the new substring.
Returns:
A new string containing the string at the specified positions.
__lt__
__lt__(self, rhs: Self) -> Bool
Compare this String to the RHS using LT comparison.
Args:
- rhs (
Self
): The other String to compare against.
Returns:
True if this String is strictly less than the RHS String and False otherwise.
__le__
__le__(self, rhs: Self) -> Bool
Compare this String to the RHS using LE comparison.
Args:
- rhs (
Self
): The other String to compare against.
Returns:
True iff this String is less than or equal to the RHS String.
__eq__
__eq__(self, other: Self) -> Bool
Compares two Strings if they have the same values.
Args:
- other (
Self
): The rhs of the operation.
Returns:
True if the Strings are equal and False otherwise.
__eq__(self, other: StringSlice[origin]) -> Bool
Compares two Strings if they have the same values.
Args:
- other (
StringSlice[origin]
): The rhs of the operation.
Returns:
True if the Strings are equal and False otherwise.
__ne__
__ne__(self, other: Self) -> Bool
Compares two Strings if they do not have the same values.
Args:
- other (
Self
): The rhs of the operation.
Returns:
True if the Strings are not equal and False otherwise.
__ne__(self, other: StringSlice[origin]) -> Bool
Compares two Strings if they have the same values.
Args:
- other (
StringSlice[origin]
): The rhs of the operation.
Returns:
True if the Strings are equal and False otherwise.
__gt__
__gt__(self, rhs: Self) -> Bool
Compare this String to the RHS using GT comparison.
Args:
- rhs (
Self
): The other String to compare against.
Returns:
True iff this String is strictly greater than the RHS String.
__ge__
__ge__(self, rhs: Self) -> Bool
Compare this String to the RHS using GE comparison.
Args:
- rhs (
Self
): The other String to compare against.
Returns:
True iff this String is greater than or equal to the RHS String.
__contains__
__contains__(self, substr: StringSlice[origin]) -> Bool
Returns True if the substring is contained within the current string.
Args:
- substr (
StringSlice[origin]
): The substring to check.
Returns:
True if the string contains the substring.
__add__
__add__(self, other: StringSlice[origin]) -> Self
Creates a string by appending a string slice at the end.
Args:
- other (
StringSlice[origin]
): The string slice to append.
Returns:
The new constructed string.
__mul__
__mul__(self, n: Int) -> Self
Concatenates the string n
times.
Args:
- n (
Int
): The number of times to concatenate the string.
Returns:
The string concatenated n
times.
__radd__
__radd__(self, other: StringSlice[origin]) -> Self
Creates a string by prepending another string slice to the start.
Args:
- other (
StringSlice[origin]
): The string to prepend.
Returns:
The new constructed string.
__iadd__
__iadd__(mut self, other: StringSlice[origin])
Appends another string slice to this string.
Args:
- other (
StringSlice[origin]
): The string to append.
copy
copy(self) -> Self
Explicitly copy the provided value.
Returns:
A copy of the value.
capacity
capacity(self) -> UInt
Get the capacity of the string.
Returns:
The capacity of the string.
write_bytes
write_bytes(mut self, bytes: Span[SIMD[uint8, 1], origin])
Write a byte span to this String.
Args:
- bytes (
Span[SIMD[uint8, 1], origin]
): The byte span to write to this String. Must NOT be null terminated.
write
write[*Ts: Writable](mut self, *args: *Ts)
Write a sequence of Writable arguments to the provided Writer.
Parameters:
- *Ts (
Writable
): Types of the provided argument sequence.
Args:
- *args (
*Ts
): Sequence of arguments to write to this Writer.
static write[*Ts: Writable](*args: *Ts, *, sep: StringSlice[StaticConstantOrigin] = __init__[__mlir_type.!kgen.string](""), end: StringSlice[StaticConstantOrigin] = __init__[__mlir_type.!kgen.string]("")) -> Self
Construct a string by concatenating a sequence of Writable arguments.
This is used only when reusing the write_to
method for
__str__
in order to avoid an endless loop recalling
the constructor:
fn write_to[W: Writer](self, mut writer: W):
writer.write_bytes(self.as_bytes())
fn __str__(self) -> String:
return String.write(self)
fn write_to[W: Writer](self, mut writer: W):
writer.write_bytes(self.as_bytes())
fn __str__(self) -> String:
return String.write(self)
Otherwise you can use the String
constructor directly without calling
the String.write
static method:
var msg = String("my message", 42, 42.2, True)
var msg = String("my message", 42, 42.2, True)
.
Parameters:
- *Ts (
Writable
): The types of the arguments to format. Each type must be satisfyWritable
.
Args:
- *args (
*Ts
): A sequence of Writable arguments. - sep (
StringSlice[StaticConstantOrigin]
): The separator used between elements. - end (
StringSlice[StaticConstantOrigin]
): The String to write after printing the elements.
Returns:
A string formed by formatting the argument sequence.
append_byte
append_byte(mut self, byte: SIMD[uint8, 1])
Append a byte to the string.
Args:
- byte (
SIMD[uint8, 1]
): The byte to append.
__iter__
__iter__(self) -> CodepointSliceIter[self]
Iterate over the string, returning immutable references.
Returns:
An iterator of references to the string elements.
__reversed__
__reversed__(self) -> CodepointSliceIter[self, False]
Iterate backwards over the string, returning immutable references.
Returns:
A reversed iterator of references to the string elements.
__len__
__len__(self) -> Int
Get the string length of in bytes.
This function returns the number of bytes in the underlying UTF-8 representation of the string.
To get the number of Unicode codepoints in a string, use
len(str.codepoints())
.
Examples
Query the length of a string, in bytes and Unicode codepoints:
from testing import assert_equal
var s = String("ನಮಸ್ಕಾರ")
assert_equal(len(s), 21)
assert_equal(len(s.codepoints()), 7)
from testing import assert_equal
var s = String("ನಮಸ್ಕಾರ")
assert_equal(len(s), 21)
assert_equal(len(s.codepoints()), 7)
Strings containing only ASCII characters have the same byte and Unicode codepoint length:
from testing import assert_equal
var s = String("abc")
assert_equal(len(s), 3)
assert_equal(len(s.codepoints()), 3)
from testing import assert_equal
var s = String("abc")
assert_equal(len(s), 3)
assert_equal(len(s.codepoints()), 3)
.
Returns:
The string length in bytes.
__str__
__str__(self) -> Self
Gets the string itself.
This method ensures that you can pass a String
to a method that
takes a Stringable
value.
Returns:
The string itself.
__repr__
__repr__(self) -> Self
Return a Mojo-compatible representation of the String
instance.
Returns:
A new representation of the string.
__fspath__
__fspath__(self) -> Self
Return the file system path representation (just the string itself).
Returns:
The file system path representation as a string.
to_python_object
to_python_object(self) -> PythonObject
Convert this value to a PythonObject.
Returns:
A PythonObject representing the value.
write_to
write_to[W: Writer](self, mut writer: W)
Formats this string to the provided Writer.
Parameters:
- W (
Writer
): A type conforming to the Writable trait.
Args:
- writer (
W
): The object to write to.
join
join[*Ts: Writable](self, *elems: *Ts) -> Self
Joins string elements using the current string as a delimiter.
Parameters:
- *Ts (
Writable
): The types of the elements.
Args:
- *elems (
*Ts
): The input values.
Returns:
The joined string.
join[T: WritableCollectionElement, //, buffer_size: Int = 4096](self, elems: List[T, hint_trivial_type]) -> Self
Joins string elements using the current string as a delimiter. Defaults to writing to the stack if total bytes of elems
is less than buffer_size
, otherwise will allocate once to the heap and write directly into that. The buffer_size
defaults to 4096 bytes to match the default page size on arm64 and x86-64, but you can increase this if you're joining a very large List
of elements to write into the stack instead of the heap.
Parameters:
- T (
WritableCollectionElement
): The types of the elements. - buffer_size (
Int
): The max size of the stack buffer.
Args:
- elems (
List[T, hint_trivial_type]
): The input values.
Returns:
The joined string.
codepoints
codepoints(self) -> CodepointsIter[self]
Returns an iterator over the Codepoint
s encoded in this string slice.
Examples
Print the characters in a string:
from testing import assert_equal
var s = String("abc")
var iter = s.codepoints()
assert_equal(iter.__next__(), Codepoint.ord("a"))
assert_equal(iter.__next__(), Codepoint.ord("b"))
assert_equal(iter.__next__(), Codepoint.ord("c"))
assert_equal(iter.__has_next__(), False)
from testing import assert_equal
var s = String("abc")
var iter = s.codepoints()
assert_equal(iter.__next__(), Codepoint.ord("a"))
assert_equal(iter.__next__(), Codepoint.ord("b"))
assert_equal(iter.__next__(), Codepoint.ord("c"))
assert_equal(iter.__has_next__(), False)
codepoints()
iterates over Unicode codepoints, and supports multibyte
codepoints:
from testing import assert_equal
# A visual character composed of a combining sequence of 2 codepoints.
var s = String("á")
assert_equal(s.byte_length(), 3)
var iter = s.codepoints()
assert_equal(iter.__next__(), Codepoint.ord("a"))
# U+0301 Combining Acute Accent
assert_equal(iter.__next__().to_u32(), 0x0301)
assert_equal(iter.__has_next__(), False)
from testing import assert_equal
# A visual character composed of a combining sequence of 2 codepoints.
var s = String("á")
assert_equal(s.byte_length(), 3)
var iter = s.codepoints()
assert_equal(iter.__next__(), Codepoint.ord("a"))
# U+0301 Combining Acute Accent
assert_equal(iter.__next__().to_u32(), 0x0301)
assert_equal(iter.__has_next__(), False)
.
Returns:
An iterator type that returns successive Codepoint
values stored in
this string slice.
codepoint_slices
codepoint_slices(self) -> CodepointSliceIter[self]
Returns an iterator over single-character slices of this string.
Each returned slice points to a single Unicode codepoint encoded in the underlying UTF-8 representation of this string.
Examples
Iterate over the character slices in a string:
from testing import assert_equal, assert_true
var s = String("abc")
var iter = s.codepoint_slices()
assert_true(iter.__next__() == "a")
assert_true(iter.__next__() == "b")
assert_true(iter.__next__() == "c")
assert_equal(iter.__has_next__(), False)
from testing import assert_equal, assert_true
var s = String("abc")
var iter = s.codepoint_slices()
assert_true(iter.__next__() == "a")
assert_true(iter.__next__() == "b")
assert_true(iter.__next__() == "c")
assert_equal(iter.__has_next__(), False)
.
Returns:
An iterator of references to the string elements.
unsafe_ptr
unsafe_ptr(self) -> UnsafePointer[SIMD[uint8, 1], mut=False, origin=self]
Retrieves a pointer to the underlying memory.
Returns:
The pointer to the underlying memory.
unsafe_ptr_mut
unsafe_ptr_mut(mut self) -> UnsafePointer[SIMD[uint8, 1], origin=self]
Retrieves a mutable pointer to the underlying memory, copying to a new buffer if this was previously pointing to a static constant.
Returns:
The pointer to the underlying memory.
unsafe_cstr_ptr
unsafe_cstr_ptr(mut self) -> UnsafePointer[SIMD[int8, 1], origin=self]
Retrieves a C-string-compatible pointer to the underlying memory.
The returned pointer is guaranteed to be null, or NUL terminated.
Returns:
The pointer to the underlying memory.
as_bytes
as_bytes(self) -> Span[SIMD[uint8, 1], self]
Returns a contiguous slice of the bytes owned by this string.
Returns:
A contiguous slice pointing to the bytes owned by this string.
as_bytes_mut
as_bytes_mut(mut self) -> Span[SIMD[uint8, 1], self]
Returns a mutable contiguous slice of the bytes owned by this string. This name has a _mut suffix so the as_bytes() method doesn't have to guarantee mutability.
Returns:
A contiguous slice pointing to the bytes owned by this string.
as_string_slice
as_string_slice(self) -> StringSlice[self]
Returns a string slice of the data owned by this string.
Returns:
A string slice pointing to the data owned by this string.
as_string_slice_mut
as_string_slice_mut(mut self) -> StringSlice[self]
Returns a mutable string slice of the data owned by this string.
Returns:
A string slice pointing to the data owned by this string.
byte_length
byte_length(self) -> Int
Get the string length in bytes.
Returns:
The length of this string in bytes.
count
count(self, substr: StringSlice[origin]) -> Int
Return the number of non-overlapping occurrences of substring substr
in the string.
If sub is empty, returns the number of empty strings between characters which is the length of the string plus one.
Args:
- substr (
StringSlice[origin]
): The substring to count.
Returns:
The number of occurrences of substr
.
find
find(self, substr: StringSlice[origin], start: Int = 0) -> Int
Finds the offset of the first occurrence of substr
starting at start
. If not found, returns -1.
Args:
- substr (
StringSlice[origin]
): The substring to find. - start (
Int
): The offset from which to find.
Returns:
The offset of substr
relative to the beginning of the string.
rfind
rfind(self, substr: StringSlice[origin], start: Int = 0) -> Int
Finds the offset of the last occurrence of substr
starting at start
. If not found, returns -1.
Args:
- substr (
StringSlice[origin]
): The substring to find. - start (
Int
): The offset from which to find.
Returns:
The offset of substr
relative to the beginning of the string.
isspace
isspace(self) -> Bool
Determines whether every character in the given String is a python whitespace String. This corresponds to Python's universal separators " \t\n\v\f\r\x1c\x1d\x1e\x85\u2028\u2029"
.
Returns:
True if the whole String is made up of whitespace characters listed above, otherwise False.
split
split(self, sep: StringSlice[origin], maxsplit: Int = -1) -> List[String]
Split the string by a separator.
Examples:
# Splitting a space
_ = String("hello world").split(" ") # ["hello", "world"]
# Splitting adjacent separators
_ = String("hello,,world").split(",") # ["hello", "", "world"]
# Splitting with maxsplit
_ = String("1,2,3").split(",", 1) # ['1', '2,3']
# Splitting a space
_ = String("hello world").split(" ") # ["hello", "world"]
# Splitting adjacent separators
_ = String("hello,,world").split(",") # ["hello", "", "world"]
# Splitting with maxsplit
_ = String("1,2,3").split(",", 1) # ['1', '2,3']
.
Args:
- sep (
StringSlice[origin]
): The string to split on. - maxsplit (
Int
): The maximum amount of items to split from String. Defaults to unlimited.
Returns:
A List of Strings containing the input split by the separator.
Raises:
If the separator is empty.
split(self, sep: NoneType = NoneType(None), maxsplit: Int = -1) -> List[String]
Split the string by every Whitespace separator.
Examples:
# Splitting an empty string or filled with whitespaces
_ = String(" ").split() # []
_ = String("").split() # []
# Splitting a string with leading, trailing, and middle whitespaces
_ = String(" hello world ").split() # ["hello", "world"]
# Splitting adjacent universal newlines:
_ = String(
"hello \t\n\v\f\r\x1c\x1d\x1e\x85\u2028\u2029world"
).split() # ["hello", "world"]
# Splitting an empty string or filled with whitespaces
_ = String(" ").split() # []
_ = String("").split() # []
# Splitting a string with leading, trailing, and middle whitespaces
_ = String(" hello world ").split() # ["hello", "world"]
# Splitting adjacent universal newlines:
_ = String(
"hello \t\n\v\f\r\x1c\x1d\x1e\x85\u2028\u2029world"
).split() # ["hello", "world"]
.
Args:
- sep (
NoneType
): None. - maxsplit (
Int
): The maximum amount of items to split from String. Defaults to unlimited.
Returns:
A List of Strings containing the input split by the separator.
splitlines
splitlines(self, keepends: Bool = False) -> List[String]
Split the string at line boundaries. This corresponds to Python's universal newlines: "\r\n"
and "\t\n\v\f\r\x1c\x1d\x1e\x85\u2028\u2029"
.
Args:
- keepends (
Bool
): If True, line breaks are kept in the resulting strings.
Returns:
A List of Strings containing the input split by line boundaries.
replace
replace(self, old: StringSlice[origin], new: StringSlice[origin]) -> Self
Return a copy of the string with all occurrences of substring old
if replaced by new
.
Args:
- old (
StringSlice[origin]
): The substring to replace. - new (
StringSlice[origin]
): The substring to replace with.
Returns:
The string where all occurrences of old
are replaced with new
.
strip
strip(self, chars: StringSlice[origin]) -> StringSlice[self]
Return a copy of the string with leading and trailing characters removed.
Args:
- chars (
StringSlice[origin]
): A set of characters to be removed. Defaults to whitespace.
Returns:
A copy of the string with no leading or trailing characters.
strip(self) -> StringSlice[self]
Return a copy of the string with leading and trailing whitespaces removed. This only takes ASCII whitespace into account: " \t\n\v\f\r\x1c\x1d\x1e"
.
Returns:
A copy of the string with no leading or trailing whitespaces.
rstrip
rstrip(self, chars: StringSlice[origin]) -> StringSlice[self]
Return a copy of the string with trailing characters removed.
Args:
- chars (
StringSlice[origin]
): A set of characters to be removed. Defaults to whitespace.
Returns:
A copy of the string with no trailing characters.
rstrip(self) -> StringSlice[self]
Return a copy of the string with trailing whitespaces removed. This only takes ASCII whitespace into account: " \t\n\v\f\r\x1c\x1d\x1e"
.
Returns:
A copy of the string with no trailing whitespaces.
lstrip
lstrip(self, chars: StringSlice[origin]) -> StringSlice[self]
Return a copy of the string with leading characters removed.
Args:
- chars (
StringSlice[origin]
): A set of characters to be removed. Defaults to whitespace.
Returns:
A copy of the string with no leading characters.
lstrip(self) -> StringSlice[self]
Return a copy of the string with leading whitespaces removed. This only takes ASCII whitespace into account: " \t\n\v\f\r\x1c\x1d\x1e"
.
Returns:
A copy of the string with no leading whitespaces.
__hash__
__hash__(self) -> UInt
Hash the underlying buffer using builtin hash.
Returns:
A 64-bit hash value. This value is not suitable for cryptographic
uses. Its intended usage is for data structures. See the hash
builtin documentation for more details.
__hash__[H: _Hasher](self, mut hasher: H)
Updates hasher with the underlying bytes.
Parameters:
- H (
_Hasher
): The hasher type.
Args:
- hasher (
H
): The hasher instance.
lower
lower(self) -> Self
Returns a copy of the string with all cased characters converted to lowercase.
Returns:
A new string where cased letters have been converted to lowercase.
upper
upper(self) -> Self
Returns a copy of the string with all cased characters converted to uppercase.
Returns:
A new string where cased letters have been converted to uppercase.
startswith
startswith(self, prefix: StringSlice[origin], start: Int = 0, end: Int = -1) -> Bool
Checks if the string starts with the specified prefix between start and end positions. Returns True if found and False otherwise.
Args:
- prefix (
StringSlice[origin]
): The prefix to check. - start (
Int
): The start offset from which to check. - end (
Int
): The end offset from which to check.
Returns:
True if the self[start:end]
is prefixed by the input prefix.
endswith
endswith(self, suffix: StringSlice[origin], start: Int = 0, end: Int = -1) -> Bool
Checks if the string end with the specified suffix between start and end positions. Returns True if found and False otherwise.
Args:
- suffix (
StringSlice[origin]
): The suffix to check. - start (
Int
): The start offset from which to check. - end (
Int
): The end offset from which to check.
Returns:
True if the self[start:end]
is suffixed by the input suffix.
removeprefix
removeprefix(self, prefix: StringSlice[origin], /) -> Self
Returns a new string with the prefix removed if it was present.
For example:
print(String('TestHook').removeprefix('Test'))
# 'Hook'
print(String('BaseTestCase').removeprefix('Test'))
# 'BaseTestCase'
print(String('TestHook').removeprefix('Test'))
# 'Hook'
print(String('BaseTestCase').removeprefix('Test'))
# 'BaseTestCase'
Args:
- prefix (
StringSlice[origin]
): The prefix to remove from the string.
Returns:
string[len(prefix):]
if the string starts with the prefix string,
or a copy of the original string otherwise.
removesuffix
removesuffix(self, suffix: StringSlice[origin], /) -> Self
Returns a new string with the suffix removed if it was present.
For example:
print(String('TestHook').removesuffix('Hook'))
# 'Test'
print(String('BaseTestCase').removesuffix('Test'))
# 'BaseTestCase'
print(String('TestHook').removesuffix('Hook'))
# 'Test'
print(String('BaseTestCase').removesuffix('Test'))
# 'BaseTestCase'
Args:
- suffix (
StringSlice[origin]
): The suffix to remove from the string.
Returns:
string[:-len(suffix)]
if the string ends with the suffix string,
or a copy of the original string otherwise.
__int__
__int__(self) -> Int
Parses the given string as a base-10 integer and returns that value. If the string cannot be parsed as an int, an error is raised.
Returns:
An integer value that represents the string, or otherwise raises.
__float__
__float__(self) -> SIMD[float64, 1]
Parses the string as a float point number and returns that value. If the string cannot be parsed as a float, an error is raised.
Returns:
A float value that represents the string, or otherwise raises.
format
format[*Ts: Stringable & Representable](self, *args: *Ts) -> Self
Format a template with *args
.
Examples:
# Manual indexing:
print(String("{0} {1} {0}").format("Mojo", 1.125)) # Mojo 1.125 Mojo
# Automatic indexing:
print(String("{} {}").format(True, "hello world")) # True hello world
# Manual indexing:
print(String("{0} {1} {0}").format("Mojo", 1.125)) # Mojo 1.125 Mojo
# Automatic indexing:
print(String("{} {}").format(True, "hello world")) # True hello world
.
Parameters:
- *Ts (
Stringable & Representable
): The types of substitution values that implementRepresentable
andStringable
(to be changed and made more flexible).
Args:
- *args (
*Ts
): The substitution values.
Returns:
The template with the given values substituted.
isdigit
isdigit(self) -> Bool
A string is a digit string if all characters in the string are digits and there is at least one character in the string.
Note that this currently only works with ASCII strings.
Returns:
True if all characters are digits and it's not empty else False.
isupper
isupper(self) -> Bool
Returns True if all cased characters in the string are uppercase and there is at least one cased character.
Returns:
True if all cased characters in the string are uppercase and there is at least one cased character, False otherwise.
islower
islower(self) -> Bool
Returns True if all cased characters in the string are lowercase and there is at least one cased character.
Returns:
True if all cased characters in the string are lowercase and there is at least one cased character, False otherwise.
isprintable
isprintable(self) -> Bool
Returns True if all characters in the string are ASCII printable.
Note that this currently only works with ASCII strings.
Returns:
True if all characters are printable else False.
rjust
rjust(self, width: Int, fillchar: StringSlice[StaticConstantOrigin] = __init__[__mlir_type.!kgen.string](" ")) -> Self
Returns the string right justified in a string of specified width.
Args:
- width (
Int
): The width of the field containing the string. - fillchar (
StringSlice[StaticConstantOrigin]
): Specifies the padding character.
Returns:
Returns right justified string, or self if width is not bigger than self length.
ljust
ljust(self, width: Int, fillchar: StringSlice[StaticConstantOrigin] = __init__[__mlir_type.!kgen.string](" ")) -> Self
Returns the string left justified in a string of specified width.
Args:
- width (
Int
): The width of the field containing the string. - fillchar (
StringSlice[StaticConstantOrigin]
): Specifies the padding character.
Returns:
Returns left justified string, or self if width is not bigger than self length.
center
center(self, width: Int, fillchar: StringSlice[StaticConstantOrigin] = __init__[__mlir_type.!kgen.string](" ")) -> Self
Returns the string center justified in a string of specified width.
Args:
- width (
Int
): The width of the field containing the string. - fillchar (
StringSlice[StaticConstantOrigin]
): Specifies the padding character.
Returns:
Returns center justified string, or self if width is not bigger than self length.
resize
resize(mut self, length: Int, fill_byte: SIMD[uint8, 1] = __init__[__mlir_type.!pop.int_literal](0))
Resize the string to a new length.
Notes:
If the new length is greater than the current length, the string is
extended by the difference, and the new bytes are initialized to
fill_byte
.
Args:
- length (
Int
): The new length of the string. - fill_byte (
SIMD[uint8, 1]
): The byte to fill any new space with.
resize(mut self, *, unsafe_uninit_length: Int)
Resizes the string to the given new size leaving any new data uninitialized.
If the new size is smaller than the current one, elements at the end are discarded. If the new size is larger than the current one, the string is extended and the new data is left uninitialized.
Args:
- unsafe_uninit_length (
Int
): The new size.
reserve
reserve(mut self, new_capacity: UInt)
Reserves the requested capacity.
Notes: If the current capacity is greater or equal, this is a no-op. Otherwise, the storage is reallocated and the data is moved.
Args:
- new_capacity (
UInt
): The new capacity in stored bytes.
Was this page helpful?
Thank you! We'll create more content like this.
Thank you for helping us improve!