简体   繁体   中英

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'. Note that the slicing starts at index 0 and stops at index 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].

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. To update the table entries as per your need, you can use the above code snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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