Numpy数组存储含%多行字符串为空问题排查
问题原因
用np.empty(1, dtype=str)创建数组时,numpy默认会生成长度为0的字符串数组(dtype='<U0'),赋值时会自动截断为空字符串,和%字符无关。
解决方法
有两种可靠的处理方式:
方法1:指定dtype=object
用object类型存储字符串,不会限制长度,适配任意长度的文本内容:
import numpy as np strings = np.empty(1, dtype=object) strings[0] = """ $_1 = %_1.a = 25129 ± 92.3741 $_2 = %_2.height = 11340.5 ± 1951.81 $_3 = %_2.center = 63.4979 ± 0.275278 $_4 = %_2.hwhm = 1.6318 ± 0.324661 $_5 = %_3.height = 19482.3 ± 2420.92 $_6 = %_3.center = 106.329 ± 0.12973 $_7 = %_3.hwhm = 1.07347 ± 0.155327 $_8 = %_4.height = 9985.67 ± 2382.35 $_9 = %_4.center = 223.417 ± 0.257358 $_10 = %_4.hwhm = -1.11065 ± 0.30902 $_11 = %_5.height = 61622 ± 2154.58 $_12 = %_5.center = 443.983 ± 0.0458769 $_13 = %_5.hwhm = 1.338 ± 0.0540433 $_14 = %_6.height = 36949.9 ± 2230.42 $_15 = %_6.center = 541.081 ± 0.0738621 $_16 = %_6.hwhm = 1.24646 ± 0.086812 $_17 = %_7.height = 28368.8 ± 2217.38 $_18 = %_7.center = 693.312 ± 0.0968789 $_19 = %_7.hwhm = 1.26497 ± 0.114331""" print(strings[0])
方法2:指定足够长度的字符串类型
如果不想用object类型,可以显式指定字符串的最大长度(比如U1000,确保能容纳目标多行字符串):
import numpy as np strings = np.empty(1, dtype='U1000') strings[0] = """ $_1 = %_1.a = 25129 ± 92.3741 $_2 = %_2.height = 11340.5 ± 1951.81 $_3 = %_2.center = 63.4979 ± 0.275278 $_4 = %_2.hwhm = 1.6318 ± 0.324661 $_5 = %_3.height = 19482.3 ± 2420.92 $_6 = %_3.center = 106.329 ± 0.12973 $_7 = %_3.hwhm = 1.07347 ± 0.155327 $_8 = %_4.height = 9985.67 ± 2382.35 $_9 = %_4.center = 223.417 ± 0.257358 $_10 = %_4.hwhm = -1.11065 ± 0.30902 $_11 = %_5.height = 61622 ± 2154.58 $_12 = %_5.center = 443.983 ± 0.0458769 $_13 = %_5.hwhm = 1.338 ± 0.0540433 $_14 = %_6.height = 36949.9 ± 2230.42 $_15 = %_6.center = 541.081 ± 0.0738621 $_16 = %_6.hwhm = 1.24646 ± 0.086812 $_17 = %_7.height = 28368.8 ± 2217.38 $_18 = %_7.center = 693.312 ± 0.0968789 $_19 = %_7.hwhm = 1.26497 ± 0.114331""" print(strings[0])
验证说明
运行上述任意一种代码,都会完整输出目标多行字符串,%字符不会造成任何影响——之前的空输出完全是因为numpy默认创建的字符串数组长度为0导致的截断。
内容的提问来源于stack exchange,提问作者srtgvinuhl
相关产品推荐
相关产品推荐

