小编Wat*_*tts的帖子

使用UTF-8的Python unicode字符串?

我从库中回来看起来是一个不正确的unicode字符串:

>>> title
u'Sopet\xc3\xb3n'
Run Code Online (Sandbox Code Playgroud)

现在,那两个十六进制转义符是U + 00F3 LATIN SMALL LETTER O WITH ACUTE的UTF-8编码.据我所知,Python中的unicode字符串应该具有实际字符,而不是字符的UTF-8编码,所以我认为这是不正确的,可能是库中或输入中的错误,对吧?

问题是,我如何(a)认识到我的unicode字符串中有UTF-8编码文本,以及(b)将其转换为正确的unicode字符串?

我对(a)感到困惑,因为对于原始字符串(即,两者都是他们自己的有效字符,u'\xc3\xb3'==³,但是它们不是应该存在的那些),编码方式没有任何错误.

看起来我可以通过eval()实现(b)前面的repr()输出减去前面的"u"来得到一个str然后用UTF-8解码str:

>>> eval(repr(title)[1:]).decode("utf-8")
u'Sopet\xf3n'
>>> print eval(repr(title)[1:]).decode("utf-8")
Sopetón
Run Code Online (Sandbox Code Playgroud)

但这似乎有些愚蠢.是否有官方认可的方法从unicode字符串中获取原始数据并将其视为常规字符串?

python unicode

7
推荐指数
2
解决办法
1万
查看次数

参数类型可能不够长(带线程)

这类似于参数类型可能活不够长?,但我对解决方案的解释似乎没有奏效.我最初的煮沸测试用例是:

use std::fmt::Debug;
use std::thread;

trait HasFeet: Debug + Send + Sync + Clone {}

#[derive(Debug, Clone)]
struct Person;

impl HasFeet for Person {}

#[derive(Debug, Copy, Clone)]
struct Cordwainer<A: HasFeet> {
    shoes_for: A,
}

impl<A: HasFeet> Cordwainer<A> {
    fn make_shoes(&self) {
        let cloned = self.shoes_for.clone();
        thread::spawn(move || {
            println!("making shoes for = {:?}", cloned);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

这给了我错误:

error[E0310]: the parameter type `A` may not live long enough
  --> src/main.rs:19:9
   |
16 | impl<A: HasFeet> Cordwainer<A> {
   | …
Run Code Online (Sandbox Code Playgroud)

rust

5
推荐指数
1
解决办法
1177
查看次数

比较字节数组和向量

我正在尝试将Vec读取的字节数与读入的字节数进行比较Vec,但是我无法将双方的类型排列在一起.这是我的代码(http://is.gd/goOnYf):

use std::io::{Cursor, Read};
// use std::borrow::Borrow;

fn main() {
    let byte_str = b"This is a byte string";
    let mut byte_vec = Vec::new();

    let mut reader = Cursor::new(byte_str.as_ref());
    reader.read_to_end(&mut byte_vec).unwrap();

    // assert_eq!(byte_str, byte_vec);
    // assert_eq!(byte_str, &byte_vec);
    // assert_eq!(byte_str, byte_vec.as_ref());
    // assert_eq!(byte_str, byte_vec.borrow());

    let bv: &[u8] = &byte_vec;
    assert_eq!(byte_str, bv);
}
Run Code Online (Sandbox Code Playgroud)

在我必须强制Vec使用let绑定的类型并比较它们之前,您可以看到我每次尝试比较它们的失败尝试.

第一个assert_eq!(byte_str, byte_vec),失败了:

`<std macros>:5:8: 5:33 error: the trait `core::cmp::PartialEq<collections::vec::Vec<u8>>` is not implemented for the type `&[u8; 21]` …
Run Code Online (Sandbox Code Playgroud)

rust

2
推荐指数
1
解决办法
1915
查看次数

标签 统计

rust ×2

python ×1

unicode ×1