简体   繁体   English

如何从 python 中的字符串中提取部分值?

[英]how do i extract a partial value from a string in python?

I have the following string:我有以下字符串:

(1, 2, 3, 4)

I want to convert it to just the last two values:我想将它转换为最后两个值:

(3, 4)

In my actual code all four fields are whole numbers but vary greatly in length.在我的实际代码中,所有四个字段都是整数,但长度差异很大。 I've tried doing this with both regex and 'for' statements as well as trying the various answers to similar questions here on SO but so far no luck.我已经尝试使用正则表达式和“for”语句来执行此操作,以及在 SO 上尝试对类似问题的各种答案,但到目前为止还没有运气。

This gives you the last two terms in your tuple:这为您提供了元组中的最后两个术语:

>> a = (1,2,3,4)
>> a[-2:]
(3,4)

It sounds like you want to use the slice operator .听起来您想使用slice 运算符

Edit: Perhaps this is a better link.编辑:也许是一个更好的链接。 Scroll down a bit for the slice notation stuff.向下滚动一下切片符号的内容。 The examples deal with strings, but it should work with any sequence type.这些示例处理字符串,但它应该适用于任何序列类型。

If (1,2,3,4) is tuple:如果 (1,2,3,4) 是元组:

data = (1,2,3,4)
newData = data[-2:]

If you have '(1,2,3,4)' then:如果你有 '(1,2,3,4)' 那么:

import ast
data = ast.literal_eval('(1,2,3,5)')
newData = data[-2:]

Or in case you have to split such list in a certain value:或者,如果您必须将此类列表拆分为某个值:

def get_slice(inputData, searchVal):   
    if searchVal in inputData and inputData.index(searchVal) < len(inputData):
        return inputData[inputData.index(searchVal)+1:]
    return ()

get_slice((1,2,3,4),2)

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

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