How do I print an OsStr without the quotes?

Viewed 1414

I'm trying to create a new name for a file path. Everything works okay, except that when I try to format OsStrs, it automatically puts them in quotes. This has been driving me crazy for hours, and no matter whether I use {:?} formatting or {:#?}, it doesn't change a thing. I also tried using .unwrap().to_str(), but that output is even worse. Does anyone know how to get rid of these quotes?

Here is my code:

use std::path::Path;

fn main() {
    let path = Path::new("/home/user/test/something.txt");
    let mut pathbuf = path.to_path_buf();
    pathbuf.set_file_name(&format!(
        "{:?}_{}.{:?}",
        path.file_stem().unwrap(),
        4,
        path.extension().unwrap()
    ));

    println!("{}", pathbuf.display());
}

This is the current output:

/home/user/test/"something"_4."txt"

But what I need it to be:

/home/user/test/something_4.txt
1 Answers

OsStr implements the Debug trait, but not Display, I think because OsStr is not guaranteed to be valid UTF-8. The OsStr::to_str method does what you want.

pathbuf.set_file_name(&format!(
    "{}_{}.{}",
    path.file_stem().unwrap().to_str().unwrap(),
    4,
    path.extension().unwrap().to_str().unwrap(),
));
Related