Bryson Noble
Bryson Noble

Reputation: 351

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. 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. Any help is appreciated!

Upvotes: 1

Views: 215

Answers (3)

Eric Chancellor
Eric Chancellor

Reputation: 126

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'

Upvotes: 0

dani herrera
dani herrera

Reputation: 51665

One line of code:

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

Upvotes: 4

Heath Raftery
Heath Raftery

Reputation: 4169

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

Upvotes: 1

Related Questions