简体   繁体   English

如何将大量数字分解为单个数字?

[英]How can I split a large number into individual digits?

I am trying to split a number such as "4378" into individual digits, then stored to a variable as a string. 我正在尝试将数字(例如“ 4378”)拆分为单个数字,然后将其作为字符串存储到变量中。 Could anyone help? 有人可以帮忙吗?

x = 4378
#code to split number
y = "4,3,7,8"

I have seen answers showing how to split a number like this and put the output into a list. 我已经看到了显示如何分割这样的数字并将输出放入列表的答案。 This will not work for my program since it will be spoken using gTTS, which cannot speak lists. 这对我的程序不起作用,因为它将使用无法朗读列表的gTTS朗读。 Any help is appreciated! 任何帮助表示赞赏!

One line of code: 一行代码:

>>> x = 4378
>>> ",".join(str(x))  # <---
'4,3,7,8'

Convert it to a string then iterate through the characters. 将其转换为字符串,然后遍历字符。 For example: 例如:

x = 4378
y = ''
for i in str(x):
    y += i + ','
y = y[:-1]
print(y)

I get: 我得到:

4,3,7,8

I seem to get the result you want using join. 我似乎得到想要使用联接的结果。

x = 12345
def numToString(x):
    y = ','.join(list(str(x)))
    return y

numToString(x)
'1,2,3,4,5'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM