.strip()方法不会删除神秘的空白字符

时间:2018-08-29 16:04:33

标签: python string strip

我正在从文件中读取一些utf-8编码的数据,如下所示:

with open (filename, 'rb') as f:
    bytes= f.read(offset, length)
    #bytes is b'hello\x00\x00\x00\x00'
    text = bytes.decode('utf-8')
    #text is 'hello    '
    stripped_text = text.strip()
    #stripped_text is 'hello    '

您可以使用

这样的简单行来重新创建它
thing = b'hello\x00\x00\x00\x00'.decode('utf8').strip()
print(thing)
#the output is 'hello    '

如您所见,尾随的nul字符没有被剥离-我认为这与.strip()无法识别'\ x00'有关,但我似乎认为应该的所有地方都可以。是什么赋予了?如何删除这些字符而不必做一些笨拙的事情?

我找不到解决此问题的帖子。

1 个答案:

答案 0 :(得分:5)

NUL不是空格,因此不带参数的# Loop over all detected circles ot the input image. for j in range(len(circle_radius_vec)): # Variables for ROI. roi_height_width = 0 roi_corner_x = 0 roi_corner_y = 0 # Calculate ROI roi_height_width = circle_radius_vec[j] roi_corner_x = center_now.x - roi_height_width/2 roi_corner_y = center_now.y - roi_height_width/2 center_now = Point(roi_height_width/2, roi_height_width/2) # Load aktuellen center point. center_now = center_vec[j] # Calculate ROI. if roi_corner_x < 0: continue if roi_corner_y < 0: continue if roi_corner_x + roi_height_width > input_img.cols: continue # Create ROI from input image. roi = Rect(roi_corner_x, roi_corner_y, roi_height_width, roi_height_width) img_roi = input_img(roi) # Create HSV representation of ROI. hsv = None cvtColor(img_roi, hsv, COLOR_BGR2HSV) 不会删除它们。您应该改用strip()

strip('\0')