0

I have a list of items that have certain values. As my list is passed along in code those values may need to be changed. I understand Insert and Add but is there some method or technique to Update or InsertAt?


How do I return a string from a regex match in python?

I am running through lines in a text file using a python script. I want to search for an img tag within the text document and return the tag as text.

When I run the regex re.match(line) it returns a _sre.SRE_MATCH object. How do I get it to return a string?

import sys
import string
import re

f = open("sample.txt", 'r' )
l = open('writetest.txt', 'w')

count = 1

for line in f:
    line = line.rstrip()
    imgtag  = re.match(r'<img.*?>',line)
    print("yo it's a {}".format(imgtag))

When run it prints:

yo it's a None
yo it's a None
yo it's a None
yo it's a <_sre.SRE_Match object at 0x7fd4ea90e578>
yo it's a None
yo it's a <_sre.SRE_Match object at 0x7fd4ea90e578>
yo it's a None
yo it's a <_sre.SRE_Match object at 0x7fd4ea90e578>
yo it's a <_sre.SRE_Match object at 0x7fd4ea90e5e0>
yo it's a None
yo it's a None
4

3 回答 3

3

如果您需要替换引用,只需分配它。

list[index] = new Item();

如果您需要更新该项目的属性,则需要对其进行强制转换。

var item = list[index] as Item;
item.Foo = bar;

我强烈建议您对通用列表使用特定类型 - 所以List<Item>,您不需要投射出来的项目。

于 2013-08-28T16:43:28.527 回答
1

您可以使用带有列表的索引器来访问特定项目

var item = list[0];

更改列表中的项目

list[0] = someobject;

假设我们有字符串列表

 List<string> lst = new List<string>();
 lst.Add("Hello");
 lst[0] = "Change hello";
于 2013-08-28T16:43:52.823 回答
0

在这种情况下,您只想更改给定索引处的项目。在该索引上使用赋值运算符,例如;

   list[index] = MyOtherReferenceOfListsType;
于 2013-08-28T16:45:46.333 回答