Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting an int to a string in Python

I want to be able to generate a number of text files with the names fileX.txt where X is some integer:

for i in range(key):     filename = "ME" + i + ".txt" //Error here! Can't concat a string and int     filenum = filename     filenum = open(filename , 'w')   

Does anyone else know how to do the filename = "ME" + i part so I get a list of files with the names: "ME0.txt" , "ME1.txt" , "ME2.txt" , and etc

like image 600
pythonTA Avatar asked Oct 15 '10 18:10

pythonTA


People also ask

Can you cast an int to a string?

We can convert int to String in java using String. valueOf() and Integer. toString() methods.

How do you convert a number to text in Python?

num2words module in Python, which converts number (like 34) to words (like thirty-four). Also, this library has support for multiple languages. In this article, we will see how to convert number to words using num2words module.

How do you convert a variable to a string in Python?

We can convert numbers to strings through using the str() method. We'll pass either a number or a variable into the parentheses of the method and then that numeric value will be converted into a string value. The quotes around the number 12 signify that the number is no longer an integer but is now a string value.

How do you cast input in Python?

As we know that Python's built-in input() function always returns a str(string) class object. So for taking integer input we have to type cast those inputs into integers by using Python built-in int() function.


1 Answers

x = 1 y = "foo" + str(x) 

Please see the Python documentation: https://docs.python.org/3/library/functions.html#str

like image 137
Florian Mayer Avatar answered Sep 28 '22 06:09

Florian Mayer