[python] Python String and Integer concatenation

I want to create string using integer appended to it, in a for loop. Like this:

for i in range(1,11):
  string="string"+i

But it returns an error:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

What's the best way to concatenate the String and Integer?

This question is related to python string integer concatenation

The answer is


for i in range(11):
    string = "string{0}".format(i)

What you did (range[1,10]) is

  • a TypeError since brackets denote an index (a[3]) or a slice (a[3:5]) of a list,
  • a SyntaxError since [1,10] is invalid, and
  • a double off-by-one error since range(1,10) is [1, 2, 3, 4, 5, 6, 7, 8, 9], and you seem to want [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

And string = "string" + i is a TypeError since you can't add an integer to a string (unlike JavaScript).

Look at the documentation for Python's new string formatting method, it is very powerful.


for i in range (1,10):
    string="string"+str(i)

To get string0, string1 ..... string10, you could do like

>>> ["string"+str(i) for i in range(11)]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9', 'string10']

for i in range[1,10]: 
  string = "string" + str(i)

The str(i) function converts the integer into a string.


I did something else. I wanted to replace a word, in lists off lists, that contained phrases. I wanted to replace that sttring / word with a new word that will be a join between string and number, and that number / digit will indicate the position of the phrase / sublist / lists of lists.

That is, I replaced a string with a string and an incremental number that follow it.

    myoldlist_1=[[' myoldword'],[''],['tttt myoldword'],['jjjj ddmyoldwordd']]
        No_ofposition=[]
        mynewlist_2=[]
        for i in xrange(0,4,1):
            mynewlist_2.append([x.replace('myoldword', "%s" % i+"_mynewword") for x in myoldlist_1[i]])
            if len(mynewlist_2[i])>0:
                No_ofposition.append(i)
mynewlist_2
No_ofposition

string = 'string%d' % (i,)

If we want output like 'string0123456789' then we can use map function and join method of string.

>>> 'string'+"".join(map(str,xrange(10)))
'string0123456789'

If we want List of string values then use list comprehension method.

>>> ['string'+i for i in map(str,xrange(10))]
['string0', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string8', 'string9']

Note:

Use xrange() for Python 2.x

USe range() for Python 3.x


Concatenation of a string and integer is simple: just use

abhishek+str(2)

You can use a generator to do this !

def sequence_generator(limit):  
    """ A generator to create strings of pattern -> string1,string2..stringN """
    inc  = 0
    while inc < limit:
        yield 'string'+str(inc)
        inc += 1

# to generate a generator. notice i have used () instead of []
a_generator  =  (s for s in sequence_generator(10))

# to generate a list
a_list  =  [s for s in sequence_generator(10)]

# to generate a string
a_string =  '['+", ".join(s for s in sequence_generator(10))+']'

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?

Examples related to concatenation

Pandas Merging 101 What does ${} (dollar sign and curly braces) mean in a string in Javascript? Concatenate two NumPy arrays vertically Import multiple csv files into pandas and concatenate into one DataFrame How to concatenate columns in a Postgres SELECT? Concatenate string with field value in MySQL Most efficient way to concatenate strings in JavaScript? How to force a line break on a Javascript concatenated string? How to concatenate two IEnumerable<T> into a new IEnumerable<T>? How to concat two ArrayLists?