Let’s say you’re writing a Python program that asks the user to enter a number, so that you can double it: >>> n = input(“Enter a number: “) Enter a number: Just doubling what we get is a bad idea, though. If the user enters “123”, then we’ll get this: >>> print(n*2)123123 What’s going on?…
Let’s say that you have a Python string, and want to grab a substring from it. The best way to do so is with a “slice”: >>> s = ‘abcdefghij’>>> print(s[3:8])defgh In the above code, we’ve defined a string. We’ve then asked for the string to be returned, starting at index 3 and up to…
Bottom line: str.isdigit returns True only for the digits 0-9 (plus superscripts like ‘\u00b2’), while str.isnumeric also returns True for numeric characters from other writing systems, such as the Chinese ‘\u4e00\u4e8c\u4e09’. A third method, str.isdecimal, is the strictest of the three. If you plan to pass the string to int(), use isdigit \u2014 int(‘\u4e8c’) raises…
In short: Put an r before the opening quote: r’c:\abc\def\ghi.txt’. In a raw string, every backslash stays a literal backslash, so Windows paths don’t get mangled by escape codes like \a, \f, or \n. Doubling each backslash works too, but raw strings save you from remembering which letters are special. I’m a Unix guy, but…
Whenever I teach Python courses, most of my students are using Windows. And thus, when it comes time to do an exercise, I inevitably end up with someone who does the following: for one_line in open(‘c:\abc\def\ghi’): print(one_line) The above code looks like it should work. But it almost certainly doesn’t. Why? Because backslashes (\) in…
As many people know, one of the mantras of the Python programming language is, “There should be one, and only one, way to do it.” (Use “import this” in your Python interactive shell to see the full list.) However, there are often times when you could accomplish something in any of several ways. In such…