pub struct PyString(/* private fields */);
Expand description
Represents a Python string
(a Unicode string object).
Values of this type are accessed via PyO3’s smart pointers, e.g. as
Py<PyString>
or Bound<'py, PyString>
.
For APIs available on str
objects, see the PyStringMethods
trait which is implemented for
Bound<'py, PyString>
.
§Equality
For convenience, [Bound<'py, PyString>
] implements PartialEq<str>
to allow comparing the
data in the Python string to a Rust UTF-8 string slice.
This is not always the most appropriate way to compare Python strings, as Python string subclasses
may have different equality semantics. In situations where subclasses overriding equality might be
relevant, use PyAnyMethods::eq
, at cost of the additional overhead of a Python method call.
use pyo3::types::PyString;
let py_string = PyString::new_bound(py, "foo");
// via PartialEq<str>
assert_eq!(py_string, "foo");
// via Python equality
assert!(py_string.as_any().eq("foo").unwrap());
Implementations§
Source§impl PyString
impl PyString
Sourcepub fn new_bound<'py>(py: Python<'py>, s: &str) -> Bound<'py, PyString>
pub fn new_bound<'py>(py: Python<'py>, s: &str) -> Bound<'py, PyString>
Creates a new Python string object.
Panics if out of memory.
Sourcepub fn intern_bound<'py>(py: Python<'py>, s: &str) -> Bound<'py, PyString>
pub fn intern_bound<'py>(py: Python<'py>, s: &str) -> Bound<'py, PyString>
Intern the given string
This will return a reference to the same Python string object if called repeatedly with the same string.
Note that while this is more memory efficient than PyString::new_bound
, it unconditionally allocates a
temporary Python string object and is thereby slower than PyString::new_bound
.
Panics if out of memory.
Sourcepub fn from_object_bound<'py>(
src: &Bound<'py, PyAny>,
encoding: &str,
errors: &str,
) -> PyResult<Bound<'py, PyString>>
pub fn from_object_bound<'py>( src: &Bound<'py, PyAny>, encoding: &str, errors: &str, ) -> PyResult<Bound<'py, PyString>>
Attempts to create a Python string from a Python bytes-like object.
Trait Implementations§
Source§impl AsPyPointer for PyString
impl AsPyPointer for PyString
Source§impl PyTypeInfo for PyString
impl PyTypeInfo for PyString
Source§fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject
fn type_object_raw(py: Python<'_>) -> *mut PyTypeObject
Source§fn is_type_of_bound(obj: &Bound<'_, PyAny>) -> bool
fn is_type_of_bound(obj: &Bound<'_, PyAny>) -> bool
object
is an instance of this type or a subclass of this type.