[英]get substring from string based on start and end position python
How do I get substring from string based on start and end position and do it for each row in a table.如何根据开始和结束位置从字符串中获取子字符串并对表中的每一行执行此操作。 the start and end positions are found in the same table at the same row as an initial string but in a different columns.
开始和结束位置与初始字符串位于同一表中的同一行,但位于不同的列中。 Input:
输入:
String Start End
1. Kids walking to school 0 3
2. Hello world 2 4
3. Today is a great day 6 9
Desired output:期望的输出:
String Start End Substring
1. Kids walking to school 0 3 Kids
2. Hello world 2 4 llo
3. Today is a great day 6 9 is a
You can use string slicing, just like you would do for a list, or any other sequence.您可以使用字符串切片,就像对列表或任何其他序列所做的一样。 For the string
string = 'Kids walking to school'
, string[0:4]
will return 'Kids'.对于字符串
string = 'Kids walking to school'
, string[0:4]
将返回 'Kids'。 Note that the slicing starts at index 0 and stops at index 3 (4 - 1).请注意,切片从索引 0 开始并在索引 3 (4 - 1) 处停止。
The following code snippet will give you a hint on how to proceed.以下代码片段将为您提供有关如何继续的提示。
table = [
('Kids walking to school', 0, 3),
('Hello world', 2, 4),
('Today is a great day', 6, 9)
]
substring = []
for line in table:
substrig.append(line[0][line[1]:line[2] + 1])
As you didn't mentioned what kind of data structure is you table and how you get it, I abstracted it with a list of tuples like (string, start, stop).由于您没有提到您的表是什么类型的数据结构以及如何获取它,我用一个元组列表抽象它,如(字符串,开始,停止)。 The idea is that for each line in table, you'll get the substring string[start:stop + 1].
这个想法是,对于表中的每一行,您将获得子字符串 string[start:stop + 1]。
table = [
['Kids walking to school', 0, 3],
['Hello world', 2, 4],
['Today is a great day', 6, 9]
]
substring = []
for line in table:
size = line[0].find(' ')
substring = line[0]
line.append(substring[0:size])
print(table)
Please use list rather using tuples datatype to hold the table values, because tuple in python are immutable datatype.请使用列表而不是使用元组数据类型来保存表值,因为python中的元组是不可变的数据类型。 To update the table entries as per your need, you can use the above code snippet.
要根据您的需要更新表条目,您可以使用上面的代码片段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.