How to Extract the First Digit in Python

In the Python programming language data stored as a string has indices that you can specify to pull out just the first character of that string. You can also use indices to just get the last character or some combination of characters such as the first five. While you cannot use indices on an integer or float in Python you can convert the number to a string and identify the first digit using its index number. Remember, Python starts counting at zero, not one, so the first digit in a string is always at index position zero.

Things You'll Need

  • Python
Show More

Instructions

    • 1

      Open the file containing the Python code you want to modify or open a Python interpreter. Open Terminal on Mac OS X or Command Prompt on Windows and type "python" to launch an interpreter. You must have Python installed on your operating system.

    • 2

      Type the following to convert the number into a string, if it is not already one:

      str('55')

      Replace '55' with your number, retaining the single quote marks.

    • 3

      Type the following to extract just the first digit:

      variable[0]

      Replace "variable" with the name of the variable containing your number.

      Type the following to extract the first digit from a converted string:

      str('55')[0]

      Replace '55' with your full number.

Related Searches:

References

Comments

Related Ads

Featured