[英]how to remove first x characters from a string in a list
So I have a list and a couple of string in it. 所以我有一个列表和几个字符串。 I just want to remove the first 7 characters from each of the strings.
我只想从每个字符串中删除前7个字符。 How do I do that?
我怎么做?
I've tried: 我试过了:
lst = ["1234567something", "1234567smthelse"]
for i in lst:
i [7:]
print lst
But I get the same list from the beginning... 但是我从一开始就得到了相同的清单...
When doing i [7:]
you are not actually editing the element of the list, you are just computing a new string, without the first 7 characters, and not doing anything with it. 当执行
i [7:]
您实际上并不是在编辑列表的元素,而是在计算一个新字符串,不包含前7个字符,并且不对其执行任何操作。
You can do this instead : 您可以改为:
>>> lst = [e[7:] for e in lst]
>>> lst
['something', 'smthelse']
This will loop on the elements of your array, and remove the characters from the beginning, as expected. 这将在数组的元素上循环,并按预期从开头删除字符。
Try this: 尝试这个:
for i in range(0, len(lst)):
lst[i] = lst[i][7:]
You can do the following: 您可以执行以下操作:
lst = ["1234567something", "1234567smthelse"]
newlst=[]
for i in lst:
newlst.append(i[7:])
print newlst
I hope that helps. 希望对您有所帮助。
i[7:]
is not inplace, it returns a new string which you are doing nothing with. i[7:]
不在原位,它返回一个新字符串,您不执行任何操作。
You can create a new list with the required string: 您可以使用所需的字符串创建一个新列表:
lst = [string[7:] for string in lst]
Or you can modify the same list: 或者,您可以修改相同的列表:
for idx, string in enumerate(ls):
ls[idx] = string[7:]
您不会在任何地方保存i[7:]
的值……只需创建一个带有修剪后的值的新列表:
lst = [i[7:] for i in lst]
尝试这个:
lst = [s[7:] for s in lst]
You never reassigned the lst in your question, which is why the output of lst in print(lst) does not change. 您从未在问题中重新分配lst,这就是为什么print(lst)中lst的输出不会更改的原因。 Try reassigning like this:
尝试像这样重新分配:
lst = ["1234567something", "1234567smthelse"]
lst = [i[7:] for i in lst]
print(lst)
returns 退货
['something', 'smthelse']
['something','smthelse']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.