Skip to content

str::escape_debug

str methods · Strings

Level: reference · for working programmers

One line: An iterator of the characters as Rust's Debug would print them — escaping control characters and quotes, leaving printable Unicode alone.

pub fn escape_debug(&self) -> EscapeDebug<'_>

Stable since 1.34.0.

This is what {:?} uses. \n becomes a backslash and an n; " and \ are escaped; printable non-ASCII is left as itself, so é stays é rather than becoming \u{e9}.

That last point is the whole difference from escape_default, which escapes everything above ASCII. Debug output stays readable for human text; default output stays ASCII-safe.

It also escapes the grapheme-extending characters at the start of a string, where they would otherwise combine with whatever precedes them in the output and corrupt the display.

The result is an iterator of char, so collect::<String>() or to_string() gives you the escaped text.

Example

str_escape_debug.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let s = "tab\there\n\"quoted\" \\ é 👋";

    println!("{}", s.escape_debug());
    println!("{s:?}");
    println!("same: {}", format!("\"{}\"", s.escape_debug()) == format!("{s:?}"));

    // Printable non-ASCII survives; escape_default would not leave it.
    println!("debug   {}", "café".escape_debug());
    println!("default {}", "café".escape_default());

    // It is an iterator of char.
    println!("{:?}", "a\nb".escape_debug().collect::<Vec<char>>());

    // A leading combining mark is escaped so it cannot merge with the output.
    println!("{}", "\u{301}x".escape_debug());
}

Verified output of str_escape_debug.rs — regenerated by tools/run_examples.py, never hand-typed.

tab\there\n\"quoted\" \\ é 👋
"tab\there\n\"quoted\" \\ é 👋"
same: true
debug   café
default caf\u{e9}
['a', '\\', 'n', 'b']
\u{301}x

See also

str::escape_debug in the standard library ↗

Po polsku

To jest dokładnie ta wersja ucieczki, której używa {:?}, i jedyna z trójki, która nie zamienia polskiego tekstu w ciąg kodów: "żółw".escape_debug() wypisze żółw, podczas gdy escape_default da \u{17c}\u{f3}\u{142}w. Ucieczce podlegają znaki sterujące oraz " i \, a drukowalne znaki spoza ASCII zostają sobą — dlatego do logów z polskimi nazwami sięga się właśnie po escape_debug (albo wprost po {:?}), a po escape_default dopiero wtedy, gdy wyjście musi być czystym ASCII. Jest jeszcze przypadek, o którym łatwo zapomnieć: znak łączący na początku łańcucha też zostaje zapisany jako sekwencja ucieczki, bo inaczej skleiłby się z tym, co w wyjściu stoi przed nim, i popsułby wyświetlanie. Wynik jest iteratorem po char, więc zwykle kończy się na .to_string() albo .collect::<String>().

Szukaj po polsku: sekwencje ucieczki · formatowanie {:?} · rust escape_debug · rust escape_default vs escape_debug