Do both strings have the same lenght? otherwise you should consider using something like:

while count < min(len(seqA), len(seqB)):

Answer from Federico Vera on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › comparing two string with a for loop and breaking when characters dont match
r/learnpython on Reddit: Comparing two string with a for loop and breaking when characters dont match
March 23, 2016 -

I'm struggling with what I need to use to get this to equal 4. The outcome down here gets me 6. I've tried a bunch of different ways to get to the problem and I'm just stuck. I'm pretty sure I'm close to the answer. Help is much appreciated user_score = 0 simon_pattern = 'RRGBRYYBGY' user_pattern = 'RRGBBRYBGY'

for c in user_pattern:
    for d in simon_pattern:
        if c == d:
            user_score += 1
        if c != d:
            break

print('User score:', user_score)

i previously had another break statement in the first if statement that got me 3

Discussions

Python string comparison whilst in loop - Stack Overflow
I am both new to this forum & programming & Python. I am trying to develop my first program, however I keep coming up against a brick wall regarding one particular issue. I am hopng that some More on stackoverflow.com
🌐 stackoverflow.com
string - While-loop within a while-loop python - Stack Overflow
I am trying to write a while-loop within a while-loop, and for some reason it is not working as it should. I know I'm probably missing something really trivial here, but I just don't understand how... More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
loops - Python: how to compare input() string to another string? - Stack Overflow
x = input("print data? (Y/N) ") while (x != 'Y' or x != 'N'): x = input("error: wrong input. Please put Y or N only ") if x == 'Y': read_serial() Trying to check whet... More on stackoverflow.com
🌐 stackoverflow.com
Python while loop with string - Stack Overflow
Your code won't work the way you state if your string really starts with a capital N. Are you sure it doesn't start with a n (lowercase)? ... Your while loop compares each character with the last, a, stopping when it finds a character that isn't equal or higher than a. More on stackoverflow.com
🌐 stackoverflow.com
January 27, 2015
🌐
CodeScracker
codescracker.com › python › program › python-program-compare-two-strings.htm
Python Program to Compare Two Strings
Therefore i+1 or 0+1 or 1 gets initialized to i. So i=1 and the condition i<lenOne again gets evaluated with new value of i. This time also the condition i<lenOne or 1<12 evaluates to be true, therefore program flow again goes inside the loop and compares the character at corresponding index of both strings · If any mismatch found, then we've initialized 1 to chk and using break keyword, the execution of while loop gets terminated.
Top answer
1 of 3
2

OK, let's take this one step at a time. First, I would read file B into a structure that's well suited for fast lookup since we're going to be doing that quite often:

chars = {}
with open("B") as lookupfile:
    for number,line in enumerate(lookupfile):
        chars[line.strip()] = number

Now we have a dictionary chars that contains letters as keys and their row number as values:

>>> chars
{'t': 1, 'a': 4, 'i': 3, 'h': 0, 's': 2}

Now we can iterate over the first file. The standard Python iterator for files consumes one line per iteration, not one character, so it's probably best to simply read the entire file into a string and then iterate over that (because for strings, iteration is character-by-character):

with open("A") as textfile:
    text = textfile.read()

Now we iterate over the string and print matching values:

for char in text:
    if char in chars:
        print("Character {0} found in row {1}".format(char, chars[char]))

If you don't like accessing the dictionary twice, you can also use

for char in text:
    found = chars.get(char):    # returns None if char isn't a key in chars
    if found:
        print("Character {0} found in row {1}".format(char, found))

or, using exceptions:

for char in text:
    try:
        print("Character {0} found in row {1}".format(char, chars[char]))
    except KeyError:
        pass
2 of 3
0
import os
fA = open('C:\\Desktop\\fileA.txt', 'r')
fB = open('C:\\Desktop\\fileB.txt', 'r')

fileb_content = []
for line in fB:
    fileb_content.append(fB.read().split('\n'))

rA = fA.readline().split('\n')[0]

for c in list(rA):
        if(c.strip()):
            if(c.lower() in fileb_content[0]):
                print(fileb_content[0].index(c.lower()))

here i test that character is not empty.

🌐
Datascienceunlimited
datascienceunlimited.tech › home › string data type in python part 2: loops and conditional expressions
String Data Type in Python Part 2: Loops and Conditional Expressions
September 25, 2019 - In Python, it is possible to construct a loop that can look at each character of a string individually. We will look at the different ways of looping over the characters of a string. First by using a while loop and then by using a for loop.
🌐
YouTube
youtube.com › painless programming
Python Strings/While Loop - YouTube
A short discussion of python strings and an example involving python strings and a while loop.
Published   September 15, 2016
Views   6K
Find elsewhere
🌐
Python.org
discuss.python.org › python help
Better while loop - Python Help - Discussions on Python.org
June 9, 2022 - Hello there 😚 I was wondering if there is a shorter or more functional way to write “while loops” in situations where you have to check multiple conditions. my problem is this while is way too long and it is hard to work with. while candle_riddle_ans.lower() != 'candle' and candle_riddle_ans.lower() != 'a candle' and candle_riddle_ans.lower() != 'the candle' and candle_riddle_ans.lower() != 'candles': i am glad to hear your suggestions.
🌐
Dot Net Perls
dotnetperls.com › while-python
Python - while Loop Examples - Dot Net Perls
March 1, 2024 - Version 1 This version of the code uses a for-loop. We loop over the strings, and sum their lengths. Version 2 Here we use the while-loop.
🌐
Python.org
discuss.python.org › python help
Help with a while loop - Python Help - Discussions on Python.org
February 5, 2024 - I need help fixing up this while loop. When I place my answer I end up with the same answer “That is not A, B, C, D or E, try again:” print("1. What is the smallest unit in life? -'2points'-") print("A: organs") print("B: cells") print("C: organism") print("D: tissues") print("E: organ system") print("---------------") organs = ("A") cells = ("B") organisms = ("C") tissues = ("D") organ_system = ("E") answers = (organs, cells, organisms, tissues, organ_system) quest1s = input("?: ") while quest...
🌐
Stack Overflow
stackoverflow.com › questions › 64563884 › python-comparison-using-while-loop
Python Comparison using While Loop - Stack Overflow
October 27, 2020 - code = "03" count = 0 npw=str(input("Enter code: ")) while count != 2: if npw == code: print("Success") break else: print("incorrect") npw=str(input("Enter code: ")) count += 1 print("Reached Maximum Tries") I want the user to have 3 tries to guess the code, but upon trying 3 tries, the third one was not read. Also, when I entered the correct code, it also prints the "Reached Maximum Tries". Thanks in Advance. ... You print "Reached Maximum Tries" because it is outside the loop.
🌐
Python.org
discuss.python.org › python help
Comparing Strings - Python Help - Discussions on Python.org
July 11, 2023 - Hello, I am attempting to teach myself Python using MIT’s OCW. I am trying to program a Hangman game using functions and I need to compare a string (letters_guessed) to the word the computer chose (secret_word (also a string)). I want to do a simple ‘if’ statement, but since I won’t ...
Top answer
1 of 4
680

For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.

Not always. NaN is a counterexample. But usually, identity (is) implies equality (==). The converse is not true: Two distinct objects can have the same value.

Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values?

You use == when comparing values and is when comparing identities.

When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is, but don't rely on it.

For boolean values, you shouldn't be doing comparisons at all. Instead of:

if x == True:
    # do something

write:

if x:
    # do something

For comparing against None, is None is preferred over == None.

I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.

Yes, that's exactly what it's for.

2 of 4
284

I would like to show a little example on how is and == are involved in immutable types. Try that:

a = 19998989890
b = 19998989889 +1
>>> a is b
False
>>> a == b
True

is compares two objects in memory, == compares their values. For example, you can see that small integers are cached by Python:

c = 1
b = 1
>>> b is c
True

You should use == when comparing values and is when comparing identities. (Also, from an English point of view, "equals" is different from "is".)