Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Convert String to Int in Python
Next article icon

In this article, we’ll explore different methods forconverting an integer to a string in Python. The most straightforward approach is using thestr() function.

Using str() Function

str()function is the simplest and most commonly used method to convert an integer to a string.

Python
n=42s=str(n)print(s)

Output
42

Explanation: str(n)convertsn to a string, resulting in '42'.

Using f-strings

For Python 3.6 or later, f-strings provide a quick way to format and convert values.

Python
n=42s=f"{n}"print(s)

Output
42

Explanation:The {n}inside the f-string automatically convertsn to a string.

Using format() Function

format() function inserts values into {} placeholders in a string. This is similar tof-strings but works with older versions of Python (before 3.6).

Python
n=42s="{}".format(n)print(s)

Output
42

Explanation:format() placesn into {}, converting it to '42'

Using %s Keyword

The %s keyword allows us to insert an integer (or any other data type) into a string. This method is part of the older style of string formatting but still works in Python.

Python
n=42s="%s"%nprint(s)

Output
42

Explanation:The %s keyword acts as a placeholder within the string and automatically converts nto a string before inserting it in place of%s.This approach can be useful for quick formatting but is less commonly used thanf-strings orformat().

Using repr() for Debugging

repr() function is usually used for debugging, as it gives a detailed string version of an object. While it also converts integers to strings, it’s not the most common method for simple integer-to-string conversion.

Python
n=42s=repr(n)print(s)

Output
42

Explanation:repr(n) returns a string '42'. It’s similar tostr()but usually used for debugging.

Related Articles:


Convert integer to string in Python

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp