Require help to obtaining a character from a given position in a string...(Python/PyQt)

StackOverflow https://stackoverflow.com/questions/23133573

  •  05-07-2023
  •  | 
  •  

Frage

I have created a basic python/PyQt program which requires the user to input a text. The program will then check if the text has a 'space' key at the beggining or end of the input. However when running the program, (even when inputting strings without spaces) it continuously returns the warning messagebox...???

the code is as follows:

answer = page.answer.text()
        # validate submitted answer...
        answerlength = (len(answer))-1
        if answer[0] or answer[answerlength] == '':
            QtGui.QMessageBox.warning(
                self, 'Error', 'Please remove the space/s before (or after) your answer!')

Note: This is a section of the written program, it is not the full program!

War es hilfreich?

Lösung 2

I don't know how python works but i think your if statement is invalid, you should use it like this:

if answer[0] == '' or answer[answerlength] == '':

Andere Tipps

You're mistakenly interpreting the or operator in python. See the following code:

answer = page.answer.text()
    # validate submitted answer...
    answerlength = (len(answer))-1
    if answer[0] == ' ' or answer[answerlength] == ' ':
        QtGui.QMessageBox.warning(
            self, 'Error', 'Please remove the space/s before (or after) your answer!')

As it is, your code evaluates to True at if answer[0], unless that position is empty, which it isn't if there's any character, including a space. The rest will never get evaluated due to the nature of or.

You can also slice the string from the end using negative slice notation:

if answer[0] == " " or answer[-1] == " ":

or use str.startswith() and str.endswith()

if answer.startswith(" ") or answer.endswith(" ")

Here's an example which checks that neither the end nor the start contain any whitespace character, using the string.whitespace, notice that you can pass tuples to str.startswith() and str.endswith().

import string
answer = page.answer.text():
    ws = tuple(string.whitespace)
    if answer.startswith(ws) or answer.endswith(ws):
        QtGui.QMessageBox.warning(
            self, 'Error', 'Please remove the space/s before (or after) your answer!')

The problem is if answer[0] or answer[answerlength] == '' will always evaluate to True since if answer[0] contains any character, it is treated as True.

You should instead do this:

if answer[0] == ' ' or answer[answerlength] == ' ':
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top