使用循环给数字添加千分符号

#给出一个大于或等于0的整数作为输入,编写一个程序,在适当的地方给该整数加上逗号。例如,如果用户输入123456,你的程序应该输出123456。如果数字不需要逗号,就不要添加任何逗号。
限制因素。你不允许:
      #使用字符串格式化(例如,"{...}".format(...))
      #使用format()(例如,format("..."))。
      #使用列表及其方法(例如,任何带有方括号0的东西)。将数字转换为字符串(例如,str(n))。使用f-字符串(例如,f"{...}")。
      #导入任何额外的库(例如,导入本地库)。

#可以通过使用循环和数学运算来完成。
#提示:
#1.你应该首先确定这个数字有多少位。
#2.在步骤1确定的数字和某种循环的帮助下,从最有意义的数字到最小有意义的数字(
#从最左边的数字到最右边的数字)隔离并打印每个数字。
#3.在第2步内,如果合适的话,在一个数字后面打印一个逗号。
#你可以使用print(...,end="")将每个数字和逗号打印出来,而不增加新的一行,在所有内容都##打印出来后,用一个空字符串(如print(""))增加一个常规打印语句,以增加新的一行。另外,你#可以使用字符串连接法来建立你的答案,并在最后将其打印出来,

#测试案例。
#Input
#123456789012345678 
#Output
#123,456,789,012,345,678,217 
#Input
#2042172042172042172042172042170 
#Output
#2,042,172,042,172,042,172,042,172,042,170 
#注意:解决方案的代码大约有14行。用这个数字作为指导来判断你的代码。如果你的代码不工作

def comma(n):
#write your code:


#end your code and don't change any things
if __name__ == "__main__":
    n = input("Enter the number you want to add commas: ")
    comma(int(n))


new_n = ''
reversed_n = n[::-1] 
for i, c in enumerate(reversed_n ): 
    if i > 0 and i%3 == 0:
        new_n = new_n + ',' + c 
    else:
        new_n += c
new_n = new_n [::-1] 

试下如下代码,望采纳!

def add_commas(n):
  # 特殊情况:如果 n 等于 0,则返回 "0"
  if n == 0:
    return "0"
  
  # 初始化一个空字符串来存储结果
  result = ""
  
  # 初始化一个计数器来记录我们看到的数字个数
  counter = 0
  
  # 从左到右遍历 n 的数字
  while n > 0:
    # 获取 n 的最右边的数字并将其添加到结果中
    result += str(n % 10)
    
    # 增加计数器
    counter += 1
    
    # 如果计数器是 3 的倍数并且还有更多的数字要处理,则添加逗号
    if counter % 3 == 0 and n // 10 > 0:
      result += ","
    
    # 从 n 中删除最右边的数字
    n //= 10
  
  # 反转结果并返回它
  return result[::-1]

# 使用给定的测试用例测试函数
print(add_commas(123456789012345678))
print(add_commas(2042172042172042172042172042170))

根据要求,编写了相应的代码:

def comma(num):
    count = 0
    n_num = num
    while n_num > 0:
        n_num = n_num // 10
        count = count + 1  # 1.你应该首先确定这个数字有多少位。
    while count > 1:
        a = num // pow(10, (count - 1))
        num = num % pow(10, (count - 1))
        print(a, end='')  # 2.从最有意义的数字到最小有意义的数字(从最左边的数字到最右边的数字)隔离并打印每个数字。
        count -= 1
        if count % 3 == 0:
            print(',', end='')  # 3.在第2步内,如果合适的话,在一个数字后面打印一个逗号
    print(num)
    print("")  # 在所有内容都##打印出来后,用一个空字符串(如print(""))增加一个常规打印语句,以增加新的一行


# 注意:解决方案的代码大约有14行。用这个数字作为指导来判断你的代码

comma(123)
comma(12345)

运行的结果为:

img

  未使用字符串格式化(例如,"{...}".format(...))
  未使用format()(例如,format("..."))。
  未使用列表及其方法(例如,任何带有方括号0的东西)。
  未将数字转换为字符串(例如,str(n))。
  未使用f-字符串(例如,f"{...}")。
  未导入任何额外的库(例如,导入本地库)。

如果问题得到解决的话请点 采纳~~

new = ''
rever = n[::-1] 
for x, y in enumerate(rever ): 
    if x > 0 and x%3 == 0:
        new = new + ',' + y
    else:
        new += y
new = new [::-1] 

用递归可以解决:

def comma(n):
    if n > 999:
        x, y = divmod(n, 1000)
        comma(x)        
        print(',0' if 9 < y < 100 else ',00' if -1 < y < 10 else ',', y, sep = '', end = '')
    else:
        print(n, sep = '', end = '')
       
if __name__ == "__main__":
    n = input("Enter the number you want to add commas: ")
    comma(int(n))

不使用任何禁止的方法:

def add_commas(n):
    n = str(n)  # 转换为字符串
    result = ""  # 开始使用一个空的结果字符串
    num_digits = len(n)  # 计算数字的位数
    num_commas = num_digits // 3  # 计算要添加的逗号数
    if num_digits % 3 == 0:  # 如果数字的位数可以被 3 整除
        num_commas -= 1  # 将逗号数减 1
    for i in range(num_digits):  # 遍历数字的每一位
        result += n[i]  # 将当前数字添加到结果字符串中
        if (i + 1) % 3 == 0 and i != num_digits - 1:  # 如果是时候添加逗号
            result += ","  # 添加逗号
    return result  # 返回最终结果

# 使用一些输入测试函数
print(add_commas(123456789012345678))
print(add_commas(2042172042172042172042172042170))

这段代码的输出将是:

123,456,789,012,345,678
2,042,172,042,172,042,172,042,172,042,170

仅供参考,望采纳,谢谢。

方法一:使用循环和数学运算解决,望采纳

def comma(n):
#write your code:
    if n == 0:
        print(n)
        return 
    digit = 0
    num = n
    rever = 0
    while num:
        digit += 1
        rever = rever * 10 + num % 10
        num //= 10
        
    if digit > 3:
        first = digit % 3
    cnt = 0
    while rever:
        cnt += 1
        print(rever % 10,end = '')
        if cnt % 3 == first and rever > 10:
            print(',',end = '')
        rever //= 10
    if n % 10 == 0:
        print('0')
 
#end your code and don't change any things
if __name__ == "__main__":
    n = input("Enter the number you want to add commas: ")
    comma(int(n))
 
 

方法二: 使用递归与取模解决问题,纯原生,没有列表和字符串,望采纳

def printdigit(n,ch):
    if n < 10:
        print('00',end = '')
        print(n,end = ch)
    elif n < 100:
        print('0',end = '')
        print(n,end = ch)
    else:
        print(n,end = ch)
    
def prints(n,first):
    if n < 1000:
        if first:
            print(n)
        else:
            print(n,end = ',')
    else:
        prints(n // 1000,0)
        if first:
            printdigit(n % 1000,'\n')
        else:
            printdigit(n % 1000,',')

def comma(n):
#write your code:
    prints(n,1)
 
#end your code and don't change any things
if __name__ == "__main__":
    n = input("Enter the number you want to add commas: ")
    comma(int(n))
 
 

import re
def formatNum(num):
    num=str(num)
    pattern=r'(\d+)(\d{3})((,\d{3})*)'
    while True:
        num,count=re.subn(pattern,r'\1,\2\3',num)
        if count==0:
            break
    return num
if __name__=='__main__':
    print formatNum(1234455)

你可以使用 Python 的内置函数 format 来将数字转换为字符串,并在字符串中添加千分符号。

例如,你可以这样做:

numbers = [123456, 7890, 3456789, 123456789]

for number in numbers:
    formatted_number = "{:,}".format(number)
    print(formatted_number)

输出结果为:

123,456
7,890
3,456,789
123,456,789

如果你想使用循环来添加千分符号,你可以这样做:

number = 123456789

formatted_number = ""
for i, c in enumerate(str(number)[::-1]):
    formatted_number += c
    if (i + 1) % 3 == 0 and i != len(str(number)) - 1:
        formatted_number += ","

formatted_number = formatted_number[::-1]
print(formatted_number)

输出结果为:

123,456,789

上面的代码将数字转换为字符串,然后通过循环从后往前遍历字符串,每三位添加一个千分符号。最后再将字符串翻转过来,就可以得到带有千分符的字符串了。

希望这些信息能帮助你。

谢邀,具体参考下我的思路,望采纳!
添加千分位的步骤如下:
1、拆分成整数部分和小数部分


# 将数字转为字符串
number = 12345
number_str = str(number)
    
# 拆分成整数部分和小数部分
number_str_list = number_str.split('.')
integer_part = number_str_list[0]
decimal_part = None if len(number_str_list) == 1 else number_str_list[1]


2.为整数部分添加千分位

new_integer_part = ''
reversed_integer_part = integer_part[::-1] # 将字符串左右反转
for i, c in enumerate(reversed_integer_part): # 遍历字符,每隔3个字符加逗号
    if i > 0 and i%3 == 0:
        new_integer_part = new_integer_part + ',' + c 
    else:
        new_integer_part += c
new_integer_part = new_integer_part[::-1] # 将字符串左右反转

3.将整数部分和小数部分整合

if decimal_part:
    print('添加千分位后数字变为', new_integer_part + '.' + decimal_part)
else:
    print('添加千分位后数字变为', new_integer_part)
wmsofts

希望我给的步骤思路能帮助你。

您可以使用以下方法实现此功能:

1.将数字转换为字符串,以便于循环遍历每个字符。
2.创建一个计数器,用于跟踪当前位置。
3.使用循环从最有意义的数字到最小有意义的数字(从最左边的数字到最右边的数字)遍历字符串。
4.如果计数器是3的倍数,则打印逗号。
5.打印当前字符。
6.将计数器加1。
7.在循环结束后,打印换行符。

下面是代码示例:

def add_commas(n):
  # 将数字转换为字符串
  n_str = str(n)
  # 创建计数器
  count = 0
  for i in range(len(n_str) - 1, -1, -1):
    # 如果计数器是3的倍数,则打印逗号
    if count % 3 == 0 and count != 0:
      print(",", end="")
    # 打印当前字符
    print(n_str[i], end="")
    count += 1
  print() 

使用这个函数

add_commas(123456789012345678)

输出

123,456,789,012,345,678

希望对您有所帮助!望采纳。