String | Modular

Mojo struct

struct String

Represents a mutable string.

This is Mojo's primary text representation, designed to efficiently handle UTF-8 encoded text while providing a safe and ergonomic interface for string manipulation.

You can create a String by assigning a string literal to a variable or with the String constructor:

# From string literals (String type is inferred)
var hello = "Hello"

# From String constructor
var world = String("World")
print(hello, world)    # "Hello World"

You can convert many Mojo types to a String because it's common to implement the Stringable trait:

var int : Int = 42
print(String(int))    # "42"

If you have a custom type you want to convert to a string, you can implement the Stringable trait like this:

@fieldwise_init
struct Person(Stringable):
    var name: String
    var age: Int

    fn __str__(self) -> String:
        return self.name + " (" + String(self.age) + ")"

var person = Person("Alice", 30)
print(String(person))      # => Alice (30)

However, print() doesn't actually specify String as its argument type. Instead, it accepts any type that conforms to the Writable trait (String conforms to this trait, which is why you can pass it to print()). That means it's actually more efficient to pass any type that implements Writable directly to print() (instead of first converting it to String). For example, float types are also writable:

var float : Float32 = 3.14
print(float)

Be aware of the following characteristics when working with String:

  • UTF-8 encoding: Strings store UTF-8 encoded text, so byte length may differ from character count. Use len(string.codepoints()) to get the codepoint count:

    var text = "café"                # 4 Unicode characters
    print(len(text))                 # Prints 5 (é is 2 bytes in UTF-8)
    print(len(text.codepoints()))    # Prints 4 (correct Unicode count)
  • Always mutable: You can modify strings in-place:

    var message = "Hello"
    message += " World"        # In-place concatenation
    print(message)             # "Hello World"

    If you want a compile-time immutable string, use comptime:

    comptime GREETING = "Immutable string"  # Fixed at compile time
    GREETING = "Not gonna happen"        # error: expression must be mutable in assignment
  • Value semantics: String assignment creates a copy, but it's optimized with copy-on-write so that the actual copying happens only if/when one of the strings is modified.

    var str1 = "Hello"
    var str2 = str1            # Currently references the same data
    str2 += " World"           # Now str2 becomes a copy of str1
    print(str1)                # "Hello"
    print(str2)                # "Hello World"

More examples:

var text = "Hello"

# String properties and indexing
print(len(text))     # 5
print(text[1])       # e
print(text[-1])      # o

# In-place concatenation
text += " World"
print(text)

# Searching and checking
if "World" in text:
    print("Found 'World' in text")

var pos = text.find("World")
if pos != -1:
    print("'World' found at position:", pos)

# String replacement
var replaced = text.replace("Hello", "Hi")   # "Hi World"
print(replaced)

# String formatting
var name = "Alice"
var age = 30
var formatted = "{} is {} years old".format(name, age)
print(formatted)    # "Alice is 30 years old"

Related functions:

Related types:

  • StringSlice: A non-owning view of string data, which can be either mutable or immutable.
  • StaticString: An alias for an immutable constant StringSlice.
  • StringLiteral: A string literal. String literals are compile-time values.

Implemented traits

AnyType, Boolable, Comparable, ConvertibleFromPython, ConvertibleToPython, Copyable, Defaultable, Equatable, FloatableRaising, Hashable, ImplicitlyCopyable, ImplicitlyDestructible, IntableRaising, Movable, PathLike, Representable, Sized, Stringable, Writable, Writer

comptime members

__copy_ctor_is_trivial

comptime __copy_ctor_is_trivial = False

__del__is_trivial

comptime __del__is_trivial = False

__move_ctor_is_trivial

comptime __move_ctor_is_trivial = True

ASCII_LETTERS

comptime ASCII_LETTERS = String.ASCII_LOWERCASE.__add__(String.ASCII_UPPERCASE)

All ASCII letters (lowercase and uppercase).

ASCII_LOWERCASE

comptime ASCII_LOWERCASE = "abcdefghijklmnopqrstuvwxyz"

All lowercase ASCII letters.

ASCII_UPPERCASE

comptime ASCII_UPPERCASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

All uppercase ASCII letters.

DIGITS

comptime DIGITS = "0123456789"

All decimal digit characters.

FLAG_HAS_NUL_TERMINATOR

comptime FLAG_HAS_NUL_TERMINATOR = (1 << (Int.BITWIDTH - 3))

Flag indicating string has accessible nul terminator.

FLAG_IS_INLINE

comptime FLAG_IS_INLINE = (1 << (Int.BITWIDTH - 1))

Flag indicating string uses inline (SSO) storage.

FLAG_IS_REF_COUNTED

comptime FLAG_IS_REF_COUNTED = (1 << (Int.BITWIDTH - 2))

Flag indicating string uses reference-counted storage.

HEX_DIGITS

comptime HEX_DIGITS = String.DIGITS.__add__("abcdef").__add__("ABCDEF")

All hexadecimal digit characters.

INLINE_CAPACITY

comptime INLINE_CAPACITY = (((Int.BITWIDTH // 8) * 3) - 1)

Maximum bytes for inline (SSO) string storage.

INLINE_LENGTH_MASK

comptime INLINE_LENGTH_MASK = (31 << String.INLINE_LENGTH_START)

Bit mask for extracting inline string length.

INLINE_LENGTH_START

comptime INLINE_LENGTH_START = (Int.BITWIDTH - 8)

Bit position where inline length field starts.

OCT_DIGITS

comptime OCT_DIGITS = "01234567"

All octal digit characters.

PRINTABLE

comptime PRINTABLE = String.DIGITS.__add__(String.ASCII_LETTERS).__add__(String.PUNCTUATION).__add__(" \t\n\r\v\f")

All printable ASCII characters.

PUNCTUATION

comptime PUNCTUATION = "!\22#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"

All ASCII punctuation characters.

REF_COUNT_SIZE

comptime REF_COUNT_SIZE = size_of[Atomic[DType.int]]()

Size of the reference count prefix for heap strings.

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 StaticString without allocating.

Args:

  • data (StringSlice): The static constant string to refer to.

@implicit __init__(out self, data: StringLiteral[data.value])

Construct a String from a StringLiteral without allocating.

Args:

  • data (StringLiteral): The static constant string to refer to.

__init__(out self, *, unsafe_from_utf8: Span[Byte, unsafe_from_utf8.origin])

Construct a string by copying the data. This constructor is explicit because it can involve memory allocation.

Consider using the String(from_utf8=...) or String(from_utf8_lossy=...) constructors instead, as they are safer alternatives to the unsafe_from_utf8 constructor.

Safety: unsafe_from_utf8 MUST be valid UTF-8 encoded data.

Args:

  • unsafe_from_utf8 (Span): The utf8 bytes to copy.

__init__(out self, *, from_utf8_lossy: Span[Byte, from_utf8_lossy.origin])

Construct a string from a span of bytes, including invalid UTF-8.

Since String is guaranteed to be valid UTF-8, invalid UTF-8 sequences are replaced with the U+FFFD replacement character: .

Examples:

# Valid UTF-8 sequence
var fire_emoji_bytes = [Byte(0xF0), 0x9F, 0x94, 0xA5]
var fire_emoji = String(from_utf8_lossy=fire_emoji_bytes)
assert_equal(fire_emoji, "🔥")

# Invalid UTF-8 sequence
# "mojo<invalid sequence>"
var mojo_bytes = [Byte(0x6D), 0x6F, 0x6A, 0x6F, 0xF0, 0x90, 0x80]
var mojo = String(from_utf8_lossy=mojo_bytes)
assert_equal(mojo, "mojo�")

Args:

  • from_utf8_lossy (Span): The bytes to convert to a string.

__init__(out self, *, from_utf8: Span[Byte, from_utf8.origin])

Construct a string from a span of bytes, raising an error if the data is not valid UTF-8.

Args:

  • from_utf8 (Span): The bytes to convert to a string.

Raises:

An error if the data is not valid UTF-8.

__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__[*Ts: Writable](out self, *args: *Ts, *, sep: StringSlice[StaticConstantOrigin] = "", end: StringSlice[StaticConstantOrigin] = "")

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"

Parameters:

  • *Ts (Writable): Types of the provided argument sequence.

Args:

  • *args (*Ts): A sequence of Writable arguments.
  • sep (StringSlice): The separator used between elements.
  • end (StringSlice): The String to write after printing the elements.

__init__[*Ts: Writable](out self, args: VariadicPack[args.is_owned, Writable, Ts], sep: StringSlice[StaticConstantOrigin] = "", end: StringSlice[StaticConstantOrigin] = "")

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")

Parameters:

  • *Ts (Writable): Types of the provided argument sequence.

Args:

  • args (VariadicPack): A VariadicPack of Writable arguments.
  • sep (StringSlice): The separator used between elements.
  • end (StringSlice): The String to write after printing the elements.

__init__(out self, *, unsafe_uninit_length: Int)

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 (Int): The number of bytes to allocate.

__init__(out self, *, unsafe_from_utf8_ptr: UnsafePointer[c_char, unsafe_from_utf8_ptr.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): An UnsafePointer[Byte] of null-terminated bytes encoded in UTF-8.

__init__(out self, *, unsafe_from_utf8_ptr: UnsafePointer[UInt8, unsafe_from_utf8_ptr.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): An UnsafePointer[Byte] of null-terminated bytes encoded in UTF-8.

__init__(out self, *, copy: Self)

Copy initialize the string from another string.

Args:

  • copy (Self): The string to copy.

__init__(out self, *, py: PythonObject)

Construct a String from a PythonObject.

Args:

Raises:

An error if the conversion failed.

__del__

__del__(deinit self)

Destroy the string data.

__bool__

__bool__(self) -> Bool

Checks if the string is not empty.

Returns:

Bool: True if the string length is greater than zero, and False otherwise.

__getitem__

__getitem__[I: Indexer, //](self, *, byte: I) -> StringSlice[origin_of(self)]

Gets a single byte at the specified byte index.

This performs byte-level indexing, not character (codepoint) indexing. For strings containing multi-byte UTF-8 characters byte must fall on a codepoint boundary and an entire codepoint will be returned. Aborts if byte does not fall on a codepoint boundary.

Parameters:

  • I (Indexer): A type that can be used as an index.

Args:

  • byte (I): The byte index (0-based). Negative indices count from the end.

Returns:

StringSlice: A StringSlice containing a single byte at the specified position.

__getitem__(self, span: ContiguousSlice) -> StringSlice[origin_of(self)]

Gets a substring at the specified byte positions.

This performs byte-level slicing, not character (codepoint) slicing. The start and end positions are byte indices. For strings containing multi-byte UTF-8 characters, slicing at byte positions that do not fall on codepoint boundaries will abort.

Args:

  • span (ContiguousSlice): A slice that specifies byte positions of the new substring.

Returns:

StringSlice: A StringSlice containing the bytes in the specified range.

__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:

Bool: True if this String is strictly less than the RHS String and False otherwise.

__eq__

__eq__(self, rhs: Self) -> Bool

Compares two Strings if they have the same values.

Args:

  • rhs (Self): The rhs of the operation.

Returns:

Bool: True if the Strings are equal and False otherwise.

__eq__(self, other: StringSlice[other.origin]) -> Bool

Compares two Strings if they have the same values.

Args:

Returns:

Bool: True if the Strings are equal and False otherwise.

__ne__

__ne__(self, other: StringSlice[other.origin]) -> Bool

Compares two Strings if they have the same values.

Args:

Returns:

Bool: True if the Strings are equal and False otherwise.

__contains__

__contains__(self, substr: StringSlice[substr.origin]) -> Bool

Returns True if the substring is contained within the current string.

Args:

Returns:

Bool: True if the string contains the substring.

__add__

__add__(self, other: StringSlice[other.origin]) -> Self

Creates a string by appending a string slice at the end.

Args:

Returns:

Self: 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:

Self: The string concatenated n times.

__radd__

__radd__(self, other: StringSlice[other.origin]) -> Self

Creates a string by prepending another string slice to the start.

Args:

Returns:

Self: The new constructed string.

__iadd__

__iadd__(mut self, other: StringSlice[other.origin])

Appends another string slice to this string.

Args:

write

static write[*Ts: Writable](*args: *Ts, *, sep: StringSlice[StaticConstantOrigin] = "", end: StringSlice[StaticConstantOrigin] = "") -> Self

Construct a string by concatenating a sequence of Writable arguments.

Parameters:

  • *Ts (Writable): Types of the provided argument sequence.

Args:

  • *args (*Ts): A sequence of Writable arguments.
  • sep (StringSlice): The separator used between elements.
  • end (StringSlice): The String to write after printing the elements.

Returns:

Self: A string formed by formatting the argument sequence.

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.

write[T: Writable](mut self, value: T)

Write a single Writable argument to the provided Writer.

Parameters:

  • T (Writable): The type of the value to write, which must implement Writable.

Args:

  • value (T): The Writable argument to write.

static write[T: Writable](value: T) -> Self

Write a single Writable argument to the provided Writer.

Parameters:

  • T (Writable): The type of the value to write, which must implement Writable.

Args:

  • value (T): The Writable argument to write.

Returns:

Self: A new String containing the written value.

capacity

capacity(self) -> Int

Get the current capacity of the String's internal buffer.

Returns:

Int: The number of bytes that can be stored before reallocation is needed.

write_string

write_string(mut self, string: StringSlice[string.origin])

Write a StringSlice to this String.

Args:

  • string (StringSlice): The StringSlice to write to this String.

append

append(mut self, codepoint: Codepoint)

Append a codepoint to the string.

Args:

  • codepoint (Codepoint): The codepoint to append.

__iter__

__iter__(self) -> CodepointSliceIter[origin_of(self)]

Iterate over the string, returning immutable references.

Returns:

CodepointSliceIter: An iterator of references to the string elements.

__reversed__

__reversed__(self) -> CodepointSliceIter[origin_of(self), False]

Iterate backwards over the string, returning immutable references.

Returns:

CodepointSliceIter: 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 = "ನಮಸ್ಕಾರ"

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 = "abc"

assert_equal(len(s), 3)
assert_equal(len(s.codepoints()), 3)

Returns:

Int: 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:

Self: The string itself.

__repr__

__repr__(self) -> Self

Return a Mojo-compatible representation of the String instance.

Returns:

Self: A new representation of the string.

__fspath__

__fspath__(self) -> Self

Return the file system path representation (just the string itself).

Returns:

Self: The file system path representation as a string.

to_python_object

to_python_object(var self) -> PythonObject

Convert this value to a PythonObject.

Returns:

PythonObject: A PythonObject representing the value.

Raises:

If the operation fails.

write_to

write_to(self, mut writer: T)

Formats this string to the provided Writer.

Args:

  • writer (T): The object to write to.

write_repr_to

write_repr_to(self, mut writer: T)

Formats this string slice to the provided Writer.

Notes: Mojo's repr always prints single quotes (') at the start and end of the repr. Any single quote inside a string should be escaped (\').

Args:

  • writer (T): The object to write to.

join

join[T: Copyable & Writable](self, elems: Span[T, elems.origin]) -> 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.

Notes:

  • Defaults to writing directly to the string if the bytes fit in an inline String, otherwise will process it by chunks.
  • 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 (Copyable & Writable): The type of the elements. Must implement the Copyable, and Writable traits.

Args:

  • elems (Span): The input values.

Returns:

Self: The joined string.

codepoints

codepoints(self) -> CodepointsIter[origin_of(self)]

Returns an iterator over the Codepoints encoded in this string slice.

Examples:

Print the characters in a string:

from testing import assert_equal, assert_raises

var s = "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"))
with assert_raises():
    _ = iter.__next__() # raises StopIteration

codepoints() iterates over Unicode codepoints, and supports multibyte codepoints:

from testing import assert_equal, assert_raises

# A visual character composed of a combining sequence of 2 codepoints.
var s = "á"
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)
with assert_raises():
    _ = iter.__next__() # raises StopIteration

Returns:

CodepointsIter: An iterator type that returns successive Codepoint values stored in this string slice.

codepoint_slices

codepoint_slices(self) -> CodepointSliceIter[origin_of(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_raises, assert_true

var s = "abc"
var iter = s.codepoint_slices()
assert_true(iter.__next__() == "a")
assert_true(iter.__next__() == "b")
assert_true(iter.__next__() == "c")
with assert_raises():
    _ = iter.__next__() # raises StopIteration

Returns:

CodepointSliceIter: An iterator of references to the string elements.

codepoint_slices_reversed

codepoint_slices_reversed(self) -> CodepointSliceIter[origin_of(self), False]

Iterates backwards over the string, returning single-character slices.

Each returned slice points to a single Unicode codepoint encoded in the underlying UTF-8 representation of this string, starting from the end and moving towards the beginning.

Returns:

CodepointSliceIter: A reversed iterator of references to the string elements.

unsafe_ptr

unsafe_ptr(self) -> UnsafePointer[Byte, origin_of(self)]

Retrieves a pointer to the underlying memory.

Returns:

UnsafePointer: The pointer to the underlying memory.

unsafe_ptr_mut

unsafe_ptr_mut(mut self, var capacity: Int = 0) -> UnsafePointer[Byte, origin_of(self)]

Retrieves a mutable pointer to the unique underlying memory. Passing a larger capacity will reallocate the string to the new capacity if larger than the existing capacity, allowing you to write more data.

Args:

  • capacity (Int): The new capacity of the string.

Returns:

UnsafePointer: The pointer to the underlying memory.

as_c_string_slice

as_c_string_slice(mut self) -> CStringSlice[origin_of(self)]

Return a CStringSlice to the underlying memory of the string.

Returns:

CStringSlice: The CStringSlice of the string.

as_bytes

as_bytes(self) -> Span[Byte, origin_of(self)]

Returns a contiguous slice of the bytes owned by this string.

Returns:

Span: A contiguous slice pointing to the bytes owned by this string.

as_bytes_mut

as_bytes_mut(mut self) -> Span[Byte, origin_of(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:

Span: A contiguous slice pointing to the bytes owned by this string.

as_string_slice

as_string_slice(self) -> StringSlice[origin_of(self)]

Returns a string slice of the data owned by this string.

Returns:

StringSlice: A string slice pointing to the data owned by this string.

byte_length

byte_length(self) -> Int

Get the string length in bytes.

Returns:

Int: The length of this string in bytes.

count_codepoints

count_codepoints(self) -> Int

Calculates the length in Unicode codepoints encoded in the UTF-8 representation of this string.

This is an O(n) operation, where n is the length of the string, as it requires scanning the full string contents.

Examples:

Query the length of a string, in bytes and Unicode codepoints:


var s = StringSlice("ನಮಸ್ಕಾರ")
assert_equal(s.count_codepoints(), 7)
assert_equal(s.byte_length(), 21)

Strings containing only ASCII characters have the same byte and Unicode codepoint length:


var s = StringSlice("abc")
assert_equal(s.count_codepoints(), 3)
assert_equal(s.byte_length(), 3)

The character length of a string with visual combining characters is the length in Unicode codepoints, not grapheme clusters:


var s = StringSlice("á")
assert_equal(s.count_codepoints(), 2)
assert_equal(s.byte_length(), 3)

Notes: This method needs to traverse the whole string to count, so it has a performance hit compared to using the byte length.

Returns:

Int: The length in Unicode codepoints.

set_byte_length

set_byte_length(mut self, new_len: Int)

Set the byte length of the String.

This is an internal helper method that updates the length field.

Args:

  • new_len (Int): The new byte length to set.

count

count(self, substr: StringSlice[substr.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:

Returns:

Int: The number of occurrences of substr.

find

find(self, substr: StringSlice[substr.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): The substring to find.
  • start (Int): The offset from which to find.

Returns:

Int: The offset of substr relative to the beginning of the string.

rfind

rfind(self, substr: StringSlice[substr.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): The substring to find.
  • start (Int): The offset from which to find.

Returns:

Int: 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:

Bool: True if the whole String is made up of whitespace characters listed above, otherwise False.

split

split(self, sep: StringSlice[sep.origin]) -> List[StringSlice[origin_of(self)]]

Split the string by a separator.

Examples:

# Splitting a space
_ = StringSlice("hello world").split(" ") # ["hello", "world"]
# Splitting adjacent separators
_ = StringSlice("hello,,world").split(",") # ["hello", "", "world"]
# Splitting with starting or ending separators
_ = StringSlice(",1,2,3,").split(",") # ['', '1', '2', '3', '']
# Splitting with an empty separator
_ = StringSlice("123").split("") # ['', '1', '2', '3', '']

Args:

Returns:

List: A List of Strings containing the input split by the separator.

split(self, sep: StringSlice[sep.origin], maxsplit: Int) -> List[StringSlice[origin_of(self)]]

Split the string by a separator.

Examples:

# Splitting with maxsplit
_ = StringSlice("1,2,3").split(",", maxsplit=1) # ['1', '2,3']
# Splitting with starting or ending separators
_ = StringSlice(",1,2,3,").split(",", maxsplit=1) # ['', '1,2,3,']
# Splitting with an empty separator
_ = StringSlice("123").split("", maxsplit=1) # ['', '123']

Args:

  • sep (StringSlice): The string to split on.
  • maxsplit (Int): The maximum amount of items to split from String.

Returns:

List: A List of Strings containing the input split by the separator.

split(self, sep: NoneType = None) -> List[StringSlice[origin_of(self)]]

Split the string by every Whitespace separator.

Examples:

# Splitting an empty string or filled with whitespaces
_ = StringSlice("      ").split() # []
_ = StringSlice("").split() # []

# Splitting a string with leading, trailing, and middle whitespaces
_ = StringSlice("      hello    world     ").split() # ["hello", "world"]
# Splitting adjacent universal newlines:
_ = StringSlice(
    "hello \t\n\v\f\r\x1c\x1d\x1e\x85\u2028\u2029world"
).split()  # ["hello", "world"]

Args:

Returns:

List: A List of Strings containing the input split by the separator.

split(self, sep: NoneType = None, *, maxsplit: Int) -> List[StringSlice[origin_of(self)]]

Split the string by every Whitespace separator.

Examples:

# Splitting with maxsplit
_ = StringSlice("1     2  3").split(maxsplit=1) # ['1', '2  3']

Args:

  • sep (NoneType): None.
  • maxsplit (Int): The maximum amount of items to split from String.

Returns:

List: A List of Strings containing the input split by the separator.

splitlines

splitlines(self, keepends: Bool = False) -> List[StringSlice[origin_of(self)]]

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:

List: A List of Strings containing the input split by line boundaries.

replace

replace(self, old: StringSlice[old.origin], new: StringSlice[new.origin]) -> Self

Return a copy of the string with all occurrences of substring old if replaced by new.

Args:

Returns:

Self: The string where all occurrences of old are replaced with new.

strip

strip(self, chars: StringSlice[chars.origin]) -> StringSlice[origin_of(self)]

Return a copy of the string with leading and trailing characters removed.

Args:

  • chars (StringSlice): A set of characters to be removed. Defaults to whitespace.

Returns:

StringSlice: A copy of the string with no leading or trailing characters.

strip(self) -> StringSlice[origin_of(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:

StringSlice: A copy of the string with no leading or trailing whitespaces.

rstrip

rstrip(self, chars: StringSlice[chars.origin]) -> StringSlice[origin_of(self)]

Return a copy of the string with trailing characters removed.

Args:

  • chars (StringSlice): A set of characters to be removed. Defaults to whitespace.

Returns:

StringSlice: A copy of the string with no trailing characters.

rstrip(self) -> StringSlice[origin_of(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:

StringSlice: A copy of the string with no trailing whitespaces.

lstrip

lstrip(self, chars: StringSlice[chars.origin]) -> StringSlice[origin_of(self)]

Return a copy of the string with leading characters removed.

Args:

  • chars (StringSlice): A set of characters to be removed. Defaults to whitespace.

Returns:

StringSlice: A copy of the string with no leading characters.

lstrip(self) -> StringSlice[origin_of(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:

StringSlice: A copy of the string with no leading whitespaces.

__hash__

__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:

Self: 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:

Self: A new string where cased letters have been converted to uppercase.

startswith

startswith(self, prefix: StringSlice[prefix.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): The prefix to check.
  • start (Int): The start offset from which to check.
  • end (Int): The end offset from which to check.

Returns:

Bool: True if the self[start:end] is prefixed by the input prefix.

endswith

endswith(self, suffix: StringSlice[suffix.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): The suffix to check.
  • start (Int): The start offset from which to check.
  • end (Int): The end offset from which to check.

Returns:

Bool: True if the self[start:end] is suffixed by the input suffix.

removeprefix

removeprefix(self, prefix: StringSlice[prefix.origin], /) -> StringSlice[origin_of(self)]

Returns a new string with the prefix removed if it was present.

Examples:

print(String('TestHook').removeprefix('Test')) # 'Hook'
print(String('BaseTestCase').removeprefix('Test')) # 'BaseTestCase'

Args:

  • prefix (StringSlice): The prefix to remove from the string.

Returns:

StringSlice: string[len(prefix):] if the string starts with the prefix string, or a copy of the original string otherwise.

removesuffix

removesuffix(self, suffix: StringSlice[suffix.origin], /) -> StringSlice[origin_of(self)]

Returns a new string with the suffix removed if it was present.

Examples:

print(String('TestHook').removesuffix('Hook')) # 'Test'
print(String('BaseTestCase').removesuffix('Test')) # 'BaseTestCase'

Args:

  • suffix (StringSlice): The suffix to remove from the string.

Returns:

StringSlice: 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:

Int: An integer value that represents the string, or otherwise raises.

Raises:

If the operation fails.

__float__

__float__(self) -> Float64

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:

Float64: A float value that represents the string, or otherwise raises.

Raises:

If the operation fails.

format

format[*Ts: Writable](self, *args: *Ts) -> Self

Produce a formatted string using the current string as a template.

The template, or "format string" can contain literal text and/or replacement fields delimited with curly braces ({}). Returns a copy of the format string with the replacement fields replaced with string representations of the args arguments.

For more information, see the discussion in the format module.

Example:

# Manual indexing:
print("{0} {1} {0}".format("Mojo", 1.125)) # Mojo 1.125 Mojo
# Automatic indexing:
print("{} {}".format(True, "hello world")) # True hello world

Parameters:

  • *Ts (Writable): The types of substitution values that implement Writable.

Args:

  • *args (*Ts): The substitution values.

Returns:

Self: The template with the given values substituted.

Raises:

If the operation fails.

is_ascii_digit

is_ascii_digit(self) -> Bool

A string is a digit string if all characters in the string are ASCII digits and there is at least one character in the string.

Note that this currently only works with ASCII strings.

Returns:

Bool: 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:

Bool: 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:

Bool: True if all cased characters in the string are lowercase and there is at least one cased character, False otherwise.

is_ascii_printable

is_ascii_printable(self) -> Bool

Returns True if all characters in the string are ASCII printable.

Note that this currently only works with ASCII strings.

Returns:

Bool: True if all characters are printable else False.

ascii_rjust

ascii_rjust(self, width: Int, fillchar: StringSlice[StaticConstantOrigin] = " ") -> Self

Returns the string right justified in a string of specified width.

Pads the string on the left with the specified fill character so that the total (byte) length of the resulting string equals width. If the original string is already longer than or equal to width, returns the original string unchanged.

Examples:

var s = String("hello")
print(s.ascii_rjust(10))        # "     hello"
print(s.ascii_rjust(10, "*"))   # "*****hello"
print(s.ascii_rjust(3))         # "hello" (no padding)

Args:

  • width (Int): The total width (in bytes) of the resulting string. This is not the amount of padding, but the final length of the returned string.
  • fillchar (StringSlice): The padding character to use (defaults to space). Must be a single-byte character.

Returns:

Self: A right-justified string of (byte) length width, or the original string if its length is already greater than or equal to width.

ascii_ljust

ascii_ljust(self, width: Int, fillchar: StringSlice[StaticConstantOrigin] = " ") -> Self

Returns the string left justified in a string of specified width.

Pads the string on the right with the specified fill character so that the total (byte) length of the resulting string equals width. If the original string is already longer than or equal to width, returns the original string unchanged.

Examples:

var s = String("hello")
print(s.ascii_ljust(10))        # "hello     "
print(s.ascii_ljust(10, "*"))   # "hello*****"
print(s.ascii_ljust(3))         # "hello" (no padding)

Args:

  • width (Int): The total width (in bytes) of the resulting string. This is not the amount of padding, but the final length of the returned string.
  • fillchar (StringSlice): The padding character to use (defaults to space). Must be a single-byte character.

Returns:

Self: A left-justified string of (byte) length width, or the original string if its length is already greater than or equal to width.

ascii_center

ascii_center(self, width: Int, fillchar: StringSlice[StaticConstantOrigin] = " ") -> Self

Returns the string center justified in a string of specified width.

Pads the string on both sides with the specified fill character so that the total length of the resulting string equals width. If the padding needed is odd, the extra character goes on the right side. If the original string is already longer than or equal to width, returns the original string unchanged.

Examples:

var s = String("hello")
print(s.center(10))        # "  hello   "
print(s.center(11, "*"))   # "***hello***"
print(s.center(3))         # "hello" (no padding)

Args:

  • width (Int): The total width (in bytes) of the resulting string. This is not the amount of padding, but the final length of the returned string.
  • fillchar (StringSlice): The padding character to use (defaults to space). Must be a single-byte character.

Returns:

Self: A center-justified string of length width, or the original string if its length is already greater than or equal to width.

resize

resize(mut self, length: Int, fill_byte: UInt8 = 0)

Resize the string to a new length. Panics if new_len does not lie on a codepoint boundary or if fill_byte is non-ascii (>=128).

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 (UInt8): The byte to fill any new space with. Must be a valid single-byte utf-8 character.

resize(mut self, *, unsafe_uninit_length: Int)

Resizes the string to the given new size leaving any new data uninitialized. Panics if the new length does not lie on a codepoint boundary.

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: Int)

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 (Int): The new capacity in stored bytes.