从列表中的字符串检索字符

2024-04-19 04:52:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含以下内容的列表:

['$GPGLL', '5305.9132', 'N', '00019.1938', 'E', '', 'A', 'A*46\r\n']

例如,我需要检索第二项的前2位数字,因此得到“53”。我需要对相当多的数据块执行类似的操作

我知道如何从列表中获取第二项,也知道如何从字符串中获取特定字符,但是将两者结合起来

tms = "$GPGLL,5305.9132,N,00019.1938,E,,A,A*46\r\n"                                  
bits = tms.split(',')
print(bits)
temp = (bits[1])
print(temp[0:2])

这段代码达到了预期的效果,但是使用一个临时变量在两个步骤中实现我想要的效果似乎不太好

有更好的办法吗


Tags: 数据字符串代码列表步骤数字字符temp
1条回答
网友
1楼 · 发布于 2024-04-19 04:52:45

如果需要,可以将两个下标合并在一行中:

print(bits[1][0:2])

尽管在a comment中提到@ujhuyz0110

I don't see doing it in 2 steps a problem though. It actually makes code easier to read instead. If there's some special meaning for the 2nd element in the list, you can give it a more meaningful name. I think the 2nd element could probably be named latitude here?

相关问题 更多 >