Начал изучать Python около 5 часов назад, но я думаю, что придумал что-то для целых чисел (извините, не мог найти числа с плавающей запятой). Я учусь в старшей школе, поэтому большой шанс, что код станет более эффективным; Я просто сделал что-то с нуля, что имело смысл для меня. Если у кого-нибудь есть какие-либо идеи о том, как улучшить работу, и достаточно объяснений, как это работает, дайте мне знать!
# Inserts comma separators
def place_value(num):
perm_num = num # Stores "num" to ensure it cannot be modified
lis_num = list(str(num)) # Makes "num" into a list of single-character strings since lists are easier to manipulate
if len(str(perm_num)) > 3:
index_offset = 0 # Every time a comma is added, the numbers are all shifted over one
for index in range(len(str(perm_num))): # Converts "perm_num" to string so len() can count the length, then uses that for a range
mod_index = (index + 1) % 3 # Locates every 3 index
neg_index = -1 * (index + 1 + index_offset) # Calculates the index that the comma will be inserted at
if mod_index == 0: # If "index" is evenly divisible by 3
lis_num.insert(neg_index, ",") # Adds comma place of negative index
index_offset += 1 # Every time a comma is added, the index of all items in list are increased by 1 from the back
str_num = "".join(lis_num) # Joins list back together into string
else: # If the number is less than or equal to 3 digits long, don't separate with commas
str_num = str(num)
return str_num