mirror of
https://github.com/RustPython/RustPython.git
synced 2026-10-29 19:24:57 +08:00
Add str.__format__
This commit is contained in:
2 files changed
+21
-4
No files matched your search
+10
-3
@@ -422,7 +422,7 @@ impl FormatSpec {
|
||||
}
|
||||
};
|
||||
|
||||
self.format_sign_and_align(magnitude_string, sign_str)
|
||||
self.format_sign_and_align(&magnitude_string, sign_str)
|
||||
}
|
||||
|
||||
pub fn format_int(&self, num: &BigInt) -> Result<String, &'static str> {
|
||||
@@ -486,12 +486,19 @@ impl FormatSpec {
|
||||
},
|
||||
};
|
||||
|
||||
self.format_sign_and_align(magnitude_string, sign_str)
|
||||
self.format_sign_and_align(&magnitude_string, sign_str)
|
||||
}
|
||||
|
||||
pub fn format_string(&self, s: &str) -> Result<String, &'static str> {
|
||||
match self.format_type {
|
||||
Some(FormatType::String) | None => self.format_sign_and_align(s, ""),
|
||||
_ => Err("Unknown format code for object of type 'str'"),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_sign_and_align(
|
||||
&self,
|
||||
magnitude_string: String,
|
||||
magnitude_string: &str,
|
||||
sign_str: &str,
|
||||
) -> Result<String, &'static str> {
|
||||
let align = self.align.unwrap_or(FormatAlign::Right);
|
||||
|
||||
+11
-1
@@ -26,7 +26,7 @@ use crate::cformat::{
|
||||
CFormatPart, CFormatPreconversor, CFormatQuantity, CFormatSpec, CFormatString, CFormatType,
|
||||
CNumberType,
|
||||
};
|
||||
use crate::format::{FormatParseError, FormatPart, FormatPreconversor, FormatString};
|
||||
use crate::format::{FormatParseError, FormatPart, FormatPreconversor, FormatSpec, FormatString};
|
||||
use crate::function::{single_or_tuple_any, OptionalArg, PyFuncArgs};
|
||||
use crate::pyhash;
|
||||
use crate::pyobject::{
|
||||
@@ -727,6 +727,16 @@ impl PyString {
|
||||
}
|
||||
}
|
||||
|
||||
#[pymethod(name = "__format__")]
|
||||
fn format_str(&self, spec: PyStringRef, vm: &VirtualMachine) -> PyResult<String> {
|
||||
match FormatSpec::parse(spec.as_str())
|
||||
.and_then(|format_spec| format_spec.format_string(&self.value))
|
||||
{
|
||||
Ok(string) => Ok(string),
|
||||
Err(err) => Err(vm.new_value_error(err.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Return a titlecased version of the string where words start with an
|
||||
/// uppercase character and the remaining characters are lowercase.
|
||||
#[pymethod]
|
||||
|
||||
Reference in new issue
Block a user