为什么字符串搜索十六进制数字 \x42 找不到星号字符?

问题描述 投票:0回答:1

我有一个包含“#”和“*”字符的列的数据框:

import pandas as pd

data = {'id': [0, 1, 2, 3], 
        'foo': ["1#", "2*", "3#", "4*"]
        }

df = pd.DataFrame(data)
print(df)
   id foo
0   0  1#
1   1  2*
2   2  3#
3   3  4*

如果我使用 ascii 表中的十六进制数字 \x23 搜索“#”,它会返回包含 1# 和 3# 的行:

print(df.loc[ df['foo'].str.contains('\x23') ])
   id foo
0   0  1#
2   2  3#

但是,如果我使用十六进制数字 \x42 搜索星号,则不会返回任何内容:

print(df.loc[ df['foo'].str.contains('\x42') ])
Empty DataFrame
Columns: [id, foo]
Index: []

我可以改用“*”来查找正确的行,但为什么十六进制数字搜索找不到任何内容?

print(df.loc[ df['foo'].str.contains('\*') ])
   id foo
1   1  2*
3   3  4*
pandas string hex contains
1个回答
0
投票

因为十六进制的

*
x2a

print (hex(ord('*')))
0x2a

print(df.loc[ df['foo'].str.contains(r'\x2a') ])
   id foo
1   1  2*
3   3  4*

hex
42
B

data = {'id': [0, 1, 2, 3], 
        'foo': ["1#", "2*", "3B", "4*"]
        }

df = pd.DataFrame(data)

print(df.loc[ df['foo'].str.contains('\x42') ])
   id foo
2   2  3B

print (chr(int('0x42', 0)))
B
© www.soinside.com 2019 - 2024. All rights reserved.