I want to find certain segments of a string and store them, however, I will need to store a large number of these strings and I was thinking that it might be more elegant to store them as indices of the master string rather than as a list of strings. I am having trouble retrieving the indices for use. For example:
index1 = [0:3, 4:8] #invalid syntax
index2 = ['0:3','5:6']
s = 'ABCDEFGHIJKLMN'
print(s[index2[0]]) #TypeError string indices must be integers
Am I thinking about this the wrong way?
Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.
To add an element to a given Python list, you can use either of the three following methods: Use the list insert method list. insert(index, element) . Use slice assignment lst[index:index] = [element] to overwrite the empty slice with a list of one element.
The elements of a list can be accessed by an index. To do that, you name the list, and then inside of a pair of square brackets you use an index number, like what I'm showing right here. 00:17 That allows access to individual elements within the list. The indexing for the list is zero-based.
The colon-based slicing syntax is only valid inside the indexing operator, e.g. x[i:j]
. Instead, you can store slice
objects in your list, where slice(x,y,z)
is equivalent to x:y:z
, e.g.
index = [slice(0,3), slice(5,6)]
print([s[i] for i in index])
will print:
['ABC', 'F']
Your idea of storing indices instead of actual substrings is a good one.
As for the mechanism, you should store the (start, end) numbers as a tuple of two integers:
index1 = [(0,3), (4,8)]
When it's time to reproduce the substring, write code like this:
pair = index1[0] # (0,3)
sub = s[pair[0] : pair[1]] # 'ABC'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With