简体   繁体   English

如何在较大字符串中的两个特殊字符之间找到字符串?

[英]How to find a string between two special characters in a larger string?

I have a code that generates the result in a string format.我有一个以字符串格式生成结果的代码。 The format is given by:格式如下:

variable[a,b] 

where a and b are two different numbers in the string.其中 a 和 b 是字符串中的两个不同数字。 For example, in the following there are some results:例如,在下面有一些结果:

result = "variable[21,30]"
result = "variable[19,27]"
result = "variable[11,16]"

My goal is to take the second number in the string.我的目标是取字符串中的第二个数字。 In the examples, the second number is 30, 27, and 16. To find them I have used the easy below code:在示例中,第二个数字是 30、27 和 16。为了找到它们,我使用了下面的简单代码:

second number = result[12:14]

In these cases, all numbers are two digits.在这些情况下,所有数字都是两位数。 So I know that the second number is between the character 12 and 14 of the string.所以我知道第二个数字在字符串的字符 12 和 14 之间。 But, my problem has arisen when the digit of the numbers can be in the range of one to 4 digits.但是,当数字的位数可以在 1 到 4 位数之间时,我的问题就出现了。 Therefore, I don't know the location of the second number in the string !.因此,我不知道字符串中第二个数字的位置!。 For example:例如:

result = "variable[1,230]"
result = "variable[19,2]"
result = "variable[61,1672]"

So, how can I find the second number?那么,我怎样才能找到第二个数字呢?

I know that the second number is between the character "," and "]".我知道第二个数字在字符“,”和“]”之间。 Therefore, I am thinking about a way that makes it possible for me to take a part of a string by specific symbols instead of the location.因此,我正在考虑一种方法,使我可以通过特定符号而不是位置来获取字符串的一部分。 I know that the below code is not correct but just for an example, instead of defining a range, define the symbols as below:我知道下面的代码是不正确的,但只是作为一个例子,而不是定义一个范围,定义如下符号:

second number = result[ "," : "]" ]

您可以使用以下代码:

second_number = result.split(',')[1][:-1]

Well, when you want to find the location of specific characters in a string you can use the find() method.好吧,当您想查找字符串中特定字符的位置时,您可以使用 find() 方法。

Thus when looking for the second number, your code should look like:因此,在查找第二个数字时,您的代码应如下所示:

start = result.find(",")
end = result.find("]")
second_number = result[start+1:end]

Take care小心

You can use re.split() method:您可以使用 re.split() 方法:

>>> import re
>>> values = re.split(r'[\[\],]', result)
>>> values
['variable', '1', '230', '']
>>> second_number = int(values[-2])
>>> second_number
230

or或者

 >>> second_number = re.split(r'[\[\],]', result)[-2]
 '230'

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

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