Comparing consequent strings in Python

trynacode

Right now I have a string array and I want to loop through the string array and compare the value at one index with the value at the next index. For example, if I was doing this in Java, the code would be something like this:

string[] some = ["IP", "IP", "ADDRESS", "2342.42.2", "IP", "ASDF"];
for (int i = 0 ; i < some.length() ; i++)
    if (some[i] == "IP" && some[i+1] == "ADDRESS")
        int ipaddress = some[i+2];

I know that Python is a bit different, but basically I am trying to find the first IP ADDRESS. How can I compare the current element and the next one in a loop?

Bhargav Rao

This is a direct translation of your code. In python enumerate iterates over a list as index,value pairs.

>>> some = ["IP", "IP", "ADDRESS", "2342.42.2", "IP", "ASDF"];
>>> for i,v in enumerate(some):
...     if v=="IP" and some[i+1] == "ADDRESS": 
...         ipaddress = some[i+2]
... 
>>> ipaddress
'2342.42.2'

However you may consider end cases where there is no such stuff. So you may as well so for i,v in enumerate(some[:-2]). This will ensure that you will not get out of the bounds of the list otherwise you will get an IndexError

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Comparing date strings in python

From Dev

Python : Error in comparing strings

From Dev

comparing occurrence of strings in list in python

From Dev

python: comparing strings in a different order

From Java

Nested list comprehension understanding for comparing strings in python

From Dev

Python Comparing two lists of strings for similarities

From Dev

Python Comparing two lists of strings for similarities

From Dev

Comparing a string with a list of strings to find anagrams in Python

From Dev

What does < or > mean in python while comparing strings

From Dev

Python 3: For loop comparing strings in lists

From Dev

Comparing strings

From Dev

how to reduce the processing cost of comparing many strings together in Python?

From Dev

Python: Comparing strings in a list with two different list lengths

From Dev

Comparing strings in huge lists but cannot use set in Python

From Dev

comparing strings to certain pattern

From Dev

comparing strings with "<" or ">" operators (C)

From Dev

Comparing Strings in Swift

From Dev

Comparing strings to search string?

From Dev

Java: comparing strings with "-"(dash)

From Dev

method for comparing strings in php

From Dev

Comparing Strings in VBA

From Dev

Comparing Strings in Batch

From Dev

Splitting and comparing strings with batch

From Dev

GoogleCloudMessaging bundle and comparing strings

From Dev

Comparing Strings compareTo in java

From Dev

Comparing two strings in Bash

From Dev

Comparing numeric strings

From Dev

Comparing Strings in .NET

From Dev

Comparing two strings with SPARQL