zaro

How do you add a digit to a number in Python?

Published in String Manipulation 2 mins read

To "add a digit" to a number in Python, you generally mean to append a digit to the right of the number, effectively changing its value. This is done by treating the number as a string and then concatenating the new digit as a string.

Here's how you can achieve this:

Using String Concatenation

The reference provided demonstrates this technique effectively:

# 1. number = str(14) + str(5)
# 2. print(number)

Explanation:

  1. Convert to String: We first convert both the original number (e.g., 14) and the digit we want to add (e.g., 5) into strings using the str() function. This is crucial because you cannot directly concatenate an integer with a string in Python.
  2. Concatenation: We then use the + operator to concatenate these string representations. The + operator, when used with strings, appends the second string to the end of the first string.
  3. Result: The resultant string is then stored in a variable, ready to be used.
  4. Output: The example code then prints the resultant string '145'.

Example

original_number = 123
digit_to_add = 4

new_number_string = str(original_number) + str(digit_to_add)
print(new_number_string) # Output: 1234

new_number_int = int(new_number_string) # Convert to int if needed
print(new_number_int) # Output: 1234

Alternative Method:

While not explicitly demonstrated in the provided reference, you can achieve the same result using f-strings, especially when dealing with variables:

original_number = 789
digit_to_add = 0

new_number_string = f"{original_number}{digit_to_add}"
print(new_number_string)  # Output: 7890

Key Takeaways

  • Type Conversion is Essential: You must convert numbers to strings before concatenating digits.
  • String Concatenation: The + operator is used for string concatenation.
  • Flexibility: You can easily append multiple digits using this method.

Practical Considerations

  • If you need the result as an integer again, use the int() function to convert the concatenated string back into a number, as demonstrated above.
  • This operation does not perform mathematical addition but string concatenation, so it should be used to append digits to the end of the number's textual representation.