I am using the NumPy array to store the string. However, I want to delete the index from 0 to n in the string. I tried multiple approaches but did not get the proper result. Can anyone help me with this?
for eg, if the length of the string is 1929 and want to delete index 1 to 1000 from the string.
arr=np.array([])
print(type(arr))
Can anyone help me with this?
CodePudding user response:
You should read the targeted substring into the same array using slicing.
array = ['a','b','c','d','e','f']
array = array[3:] # new values of array = ['d','e','f']
I deleted the first 3 letters.
CodePudding user response:
Slicing an array in Python is quite straightforward, the syntax is variable[starting_index:ending_index]
. You can leave either index blank to basically get "the rest" of the array
# starting array
arr1 = ["h", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d"]
print(arr1)
# everything after 6th element
arr2 = arr1[6:]
print(arr2)
# elements 6th, 7th and 8th only
arr3 = arr1[6:9]
print(arr3)
result:
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
['w', 'o', 'r', 'l', 'd']
['w', 'o', 'r']
CodePudding user response:
Deleting a range of characters from a string
although some answers have been posted with very short and efficient code, I wanted to explain a "more algorithmic" solution that can be used (with obvious modifications) in many languages.
a_string = "this_is_a_string"
n = 4
string_len = len(a_string)
# you have to delete characters from 0 to n (4 in this example)
# obviously you can't delete the characters "normally"
# because then the indexes of the elements will change later on
rev_string = a_string[::-1]
# reversing the string (gnirts_a_si_siht)
arr_rev_string = list(rev_string)
# casting the string into array
for i in range(1, n 1):
del arr_rev_string[string_len-i]
# deleting characters that they were between 0-n (now they are at the bottom of the list)
my_string = "".join(arr_rev_string[::-1])
print(my_string)
# output --> _is_a_string