what is the difference between – and – in programming?

Question:

This is my code:

k = "Hello–World"

for i in k:
    if i == "-" or i.isalpha():
        pass
    else:
        print("Error = ",i)

Output:

Error =  –

In fact in my keyboard I don’t have this letter "–" instead I have this "-".

Asked By: Mounesh

||

Answers:

The difference isn’t specific to programming, they are different characters. The fact that they both are horizontal lines doesn’t change the fact that they have different meaning and are simply not the same character. What is the difference between "|", "I" and "l" in programming? (they are the pipe, Capital letter i and lowercase letter l – they don’t look like a vertical line in every character set though)

In your case, one is a hyphen ("-") and the other a so-called en-dash ("–"). The hyphen/minus is what you find on your standard US international keyboard (and most other keyboards).

If you’re wondering how the en dash got into the text in the first place, this type of error is often the result of copying text between a word processor and a text editor. For example, MS Word will turn two consecutive hyphens (minuses) into an en dash.

Try typing (not copying and pasting) That is -- surprising. into Word and you’ll find that it now has That is – surprising. (with an en dash). If you copy that text and paste it into a text editor (that supports the needed encoding, likely utf-8), you will end up with the en dash in your text/code.

This is why you shouldn’t use a word processor (be it Word, WordPad, etc.) to write code, but instead use a text editor or IDE, configured to use a monospaced font.

Note: although using a monospaced font helps coding, it does make spotting an en dash, em dash or basic hyphen/minus a bit harder, since they all have to fit in the same space. But the advantages far outweigh such a minor (and rare) disadvantage.

Answered By: Grismar
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.