Convert Integer to String in Python

Convert integer to string in Python

>>> str(42)
'42'

>>> int('42')
42

Links to the documentation:

  • int()
  • str()

str(x) converts any object x to a string by calling x.__str__(), or repr(x) if x doesn't have a __str__() method.

python: integer to string conversion

You apparently want to print the representation of the string. Python has a builtin function repr(..) for this:

n = 357
x = str(n)
print(repr(x))

The representation of a string is a list of characters between single or double quotes (double quotes if the string contains at least one single quote and no double quotes). Furthermore if there are escape sequences (like a new line), these are printed with a backslash (like \n).

INT to STRING conversion in python

Somewhere earlier on, you did:

str = 'somestr goes here'

Never name a variable str; it causes this problem. You can correct it for now with:

del str

but the solution in the future is to never use str as a variable name.

Convert a list of integers to string

There's definitely a slicker way to do this, but here's a very straight forward way:

mystring = ""

for digit in new:
mystring += str(digit)

converting Integer to String process ( under the hood )

String to integer

Let's start with converting a string to an int, as I think it's a bit simpler to think through. I'll make a few assumptions to start:

  1. our int method will only deal with int inputs, no floats, complex numbers, etc. for now.
  2. we will only deal with positive numbers for now as well.
  3. I won't be dealing with intentionally wrong inputs, like int("Wassup")

The implementation will go through the string input from right to left, and build up the integer number by number.

def custom_int(input):
# Your intuition is right that we will need some kind of look up! this matches a character to a number
s_to_i_dict= {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}

# imagine our input is the string "123", we want to build up the number 123
# one digit at a time. If you break it down, 123 is equal to 100 + 20 + 3
# Thinking it through further, that's the same as 1*100 + 2*10 + 3*1

# So for each digit going right to left, we'll multiply it by some multiplier
# add it to our result, theb change that multiplier to handle the next digit.

multiplier = 1
output = 0

# This is a little shortcut to get you looping through a list or a string from the last element to the first:
for digit in input[::-1]:
# digit is a character, we find the corresponding number, multiply it by the multiplier, then add it to the old version of output
output = output + ( s_to_i_dict[digit] * multiplier)

# we are done with this digit, so the next multiplier should be 10 times the last (going from digits to tens to hundreds etc.)
multiplier = multiplier * 10
return output

Running this you'd get:

s_to_i("123")

123

type(s_to_i("123"))

<class 'int'>

For the "123" input, our loop will run 3 times. the first time around output will just be the rightmost digit 3, the next time around, we will add 2*10 to output, giving us 23.

The final time through the loop we will get 23 + 1*100, or 123.

Integer to string

We can apply the exact same pattern to the int to string conversion. The same assumptions apply as I won't cover all edge cases, but fundamentally we will do the same thing: go through the numbers from right to left, then build up a string representation of the number.

Now we can't loop over numbers as easily as we loop over strings, but with some good use of mod and division we can get a similar pattern. say n = 123, how do we get just the rightmost digit from the number? Well the rightmost digit is the remainder of dividing n by 10, or in code rightmost_digit = n % 10.

Once we have the rightmost digit, the next step is to try to extract the second rightmost digit, 2 in this case. There are a few ways to do that but my favorite is to recognize that we have already grabbed the rightmost digit, so we don't need it anymore

We can update our number n as follows: n = n // 10 which will give n the value of 12 instead of 123. This is called integer division, and is basically primary school division before you discovered floats :P

How does this help? well notice that 2 is the rightmost digit of 12 and we already know how to grab that! Let's put this all together in a function.

def i_to_s(input):
# Notice that this is the opposite dictionary than before. ints are the key, and they give us the character we need.
i_to_s_dict={0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9'}

# This time we want our output to be a string so we initialize an empty string
output = ""

# There are more precise ways to set up this loop, as this one creates an edge case I'll leave up to you to find, but works with _almost_ every integer :P
while(input != 0):

rightmost_digit = input % 10

# We concatenate the new character we found with the output we've accumulated so far
output = i_to_s(rightmost_digit) + output

# Change the initial number for the next iteration
input = input // 10

return output

i_to_s(123)

'123'

type(i_to_s(123))

<class 'str'>

converting list of integers ,numerical strings into a integer list

Here's how to do it below I explain with code comments.

def solve(lst):
# Dictionary of words to numbers
NUMBERS_DIC = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twelve': 12, 'thirteen': 13, 'fourteen': 14, 'fifteen': 15, 'sixteen': 16, 'seventeen': 17, 'eighteen': 18, 'nineteen': 19, 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60, 'seventy': 70, 'eighty': 80, 'ninety': 90}

# list to be returned
retLst = []
for num in lst:
# if num is an int
if type(num)==int: # type() tells you the type of the variable
retLst.append(num)
# if num is a string that is numeric
elif num.isnumeric():
retLst.append(int(num)) # Turn to int
# if num is a string word such as forty-seven"
else:
# turns "forty-seven" -> ["forty","seven"]
word_values_lst = num.split("-")
val = 0
for word in word_values_lst:
val+=NUMBERS_DIC[word] # Get value from NUMBERS_DIC
retLst.append(val)



# Sort lst
retLst.sort()


return list(set(retLst)) # removes duplicates

lst = [1, 3, '4', '1', 'three', 'eleven', 'forty-seven', '3']
retLst = solve(lst)

print(retLst)

How to convert an integer into string without using in-built function?

You can keep dividing a given integer by 10 and prepending the remainder to the output string. Use the ordinal number of '0' plus the remainder to obtain the ordinal number of the remainder, and then convert it to string using the chr function:

def int_to_string(i):
string = ''
while True:
i, remainder = divmod(i, 10)
string = chr(ord('0') + remainder) + string
if i == 0:
break
return string

so that:

print(int_to_string(0))
print(int_to_string(5))
print(int_to_string(65))
print(int_to_string(923))

would output:

0
5
65
923

Python Fast conversion from int to string

This code is faster (but not enough! :D)

result:

╔═══╦════════════╦═════════════╦══════════════╦═══════════════════╗
║ ║ Count ║ Compute(s) ║ Convert(s) ║ M.T Convert(s) ║
╠═══╬════════════╬═════════════╬══════════════╬═══════════════════╣
║ 1 ║ 100,000 ║ 2.68 ║ 3.85 ║ 2.81 ║
║ 2 ║ 250,000 ║ 21.17 ║ 39.83 ║ 21.09 ║
╚═══╩════════════╩═════════════╩══════════════╩═══════════════════╝

Anyway, I think you can do it faster with multi-threading.

import time
import math
import threading

res_dict = {}

def int_str(threadID, each_thread, max_thread):
if threadID == 1 :
res_dict[threadID] = (str(factorial // 10 ** (each_thread * (max_thread - 1))))
elif threadID == max_thread:
res_dict[threadID] = (str(int(factorial % 10 ** (each_thread * 1))))
else:
tmp = (factorial % 10 ** (each_thread * (max_thread - threadID + 1))) // 10 ** (each_thread * (max_thread - threadID))
pre = "0" * ((digits // max_thread) - (math.floor(math.log10(tmp))+1))
res_dict[threadID] = (pre + str(int(tmp)))

factorial = 1

print(" ")

def fact(a,b):
if b == 1:
return 1
else:
return a * fact(a,b-1)

one = int(input("lower = "))
two = int(input("higher = "))

start = time.time()

for x in range(one,two + 1):
factorial = factorial * two
two = two - 1

end = time.time()

print("DONE! ")
print(end - start, "Seconds to compute")

start = time.time()

digits = math.floor(math.log10(factorial))+1

max_thread = 3
each_thread = digits // max_thread

tr = []

for item in range(1, max_thread + 1):
t = threading.Thread(target=int_str, args=(item, each_thread, max_thread))
t.start()
tr.append(t)

for item in tr:
item.join()

last_res = ''

for item in sorted(res_dict):
if item != max_thread:
last_res += res_dict[item]
else:
last_res += ("0" * (digits - len(last_res) - len(res_dict[item]))) + res_dict[item]

f = open('Ans_2.txt','w')
f.write(last_res)
f.close()

end = time.time()
print(end - start, "Seconds to convert and save")

print(digits, "Digets")

update:

just run your code with pypy it's amazingly fast!

╔═══╦════════════╦═════════════╦══════════════╦═══════════════════╗
║ ║ Count ║ Compute(s) ║ Convert(s) ║ pypy Convert(s) ║
╠═══╬════════════╬═════════════╬══════════════╬═══════════════════╣
║ 1 ║ 100,000 ║ 2.98 ║ 3.85 ║ 0.79 ║
║ 2 ║ 250,000 ║ 25.83 ║ 39.83 ║ 7.17 ║
╚═══╩════════════╩═════════════╩══════════════╩═══════════════════╝


Related Topics



Leave a reply



Submit