Is there a way to slice a string in which you know the start index while only knowing which value you want to end at in Python?

Question:

I’m writing some code that returns the number of views the top Youtube video has based on the search query. The substring starts at index 101, the problem is that not all video views are listed with the same length. For example, "6.8M views" has a length of 10 while "5B views" has just 8. Is there a way to implement a string slice as shown below?

numOfViews = list[101:ends with "views"]

To be clear, I just need the first occurrence of "views" after index 101.

Asked By: BVB44

||

Answers:

Both str.index and str.find accept a start parameter. You can therefore find the first instance of "views" following index 101 using

index_of_views = string.find(" views", 101)

The substring containing the number of views is then

num_of_views = string[101:index_of_views]
Answered By: Mad Physicist
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.