/  Technology   /  Converting integer to string in Python
Converting integer to string in Python

Converting integer to string in Python

We can convert an integer into a string using the following ways

  • Using str()
  • Using %s
  • Using format()
  • Using f-string

 

1. Using str()

This function returns a string version of any object. The object can be of any type int, char, float, etc. If no object is passed, it returns an empty string. 

Example:

a = 100
print(type(a))
print("The number is:",a)

string_converted = str(a)
print(type(string_converted))
print(type("The string is",string_converted))

output:

 

2. Using %s keyword:

%s indicates a conversion type of string. It converts the given object to a string using the str() function.

Syntax: 

“%s”  %integer

Example:

a = 100
print(type(a))
print("The number is:",a)

string_converted = "% s" % a

print(type(string_converted))
print(type("The string is",string_converted))

output:

 

3. Using .format():

This method returns a formatted representation of the given object controlled by the format specifier. The format specifier specifies which type we are trying to convert the object into.

Syntax: 

 ‘{}’.format(integer)

Example:

a = 100
print(type(a))
print("The number is:",a)

string_converted = "{}".format(a)

print(type(string_converted))
print(type("The string is",string_converted))

output:

 

4. Using f-string:

The f-string is literal string interpolation or it’s a more simplified way for string formatting. 

Syntax: 

f’{integer}’

Example:

a = 100
print(type(a))
print("The number is:",a)

string_converted = f'{a}'

print(type(string_converted))
print(type("The string is",string_converted))

output:

 

Leave a comment