Practical Application

Python String index() Method function is used to extract the suffix or prefix length after or before the target word. The example below displays the total bit length of an instruction coming from AC voltage given information in a string.

Python




# initializing target strings
VOLTAGES = ["001101 AC", "0011100 DC", "0011100 AC", "001 DC"]
  
# initializing argument string
TYPE = "AC"
  
# initializing bit-length calculator
SUM_BITS = 0
  
for i in VOLTAGES:
  
    ch = i
  
    if ch[len(ch) - 2] != "D":
        # extracts the length of bits in string
        bit_len = ch.index(TYPE) - 1
  
        # adds to total
        SUM_BITS = SUM_BITS + bit_len
  
print("The total bit length of AC is : ", SUM_BITS)


Output

The total bit length of AC is : 13


Python String index() Method

Python String index() Method allows a user to find the index of the first occurrence of an existing substring inside a given string in Python.

Similar Reads

Python String Index() Method Syntax

Syntax:  string_obj.index(substring, start, end) Parameters:  substring: The string to be searched for. start (default : 0) : This function specifies the position from where the search has to be started.  end (default: length of string): This function specifies the position from where the search has to end. Return:  Returns the first position of the substring found. Exception:  Raises ValueError if the argument string is not found or the index is out of range....

Python String Index() Method Example

Here the first character of ‘and’ in string random is ‘a’ and the index of ‘a’ is 1, so the output is also 1....

Practical Application

...

Contact Us