简体   繁体   English

如何从 python 中的字符串中提取特定值?

[英]how do I extract a specific value from a string in python?

I have a string with this structure:我有一个具有这种结构的字符串:

[519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992],12,160p30

I need to find the value after ], that here is 12 .我需要找到],之后的值,这里是12 I need this value to use in a for loop.我需要这个值在for循环中使用。 how can I do this?我怎样才能做到这一点?

If all you want is at the right end of your string, you can use rsplit instead of split如果你想要的只是在你的字符串的右端,你可以使用rsplit而不是split

s = "[519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992],12,160p30"
val = s.rsplit(",", 2)[1]  # val get value "12" from s

rsplit will split your string from the right starting at the separator "," a maximum of 2 times. rsplit将从分隔符","开始的右侧拆分您的字符串,最多拆分 2 次。 As you want the second to last value of your string, use indexing to get the desired value.当您想要字符串的倒数第二个值时,请使用索引来获取所需的值。

If you have same structure of data you can use regexp to extract part of strings you need to use.如果你有相同的数据结构,你可以使用正则表达式来提取你需要使用的部分字符串。 In described case it can be done like this:在描述的情况下,可以这样做:

import re


test_string = '[519.1743772241992, 519.1743772241992, 519.1743772241992, '\
                '519.1743772241992, 519.1743772241992, 519.1743772241992],'\
                '12,160p30'

pattern = r'(^\[.+\]),([0-9]+),(.+$)'

result = re.search(pattern, test_string)

print(result.group(1))
# [519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992]

print(result.group(2))
# 12

print(result.group(3))
# 160p30
string = "[519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992, 519.1743772241992],1,160p30"
i = string.rfind("],") + 2
value = int(string[i : string.find(",", i)])
print(value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM