Append an int to string python

Python supports string concatenation using + operator. In most of the programming languages, if we concatenate a string with an integer or any other primitive data types, the language takes care of converting them to string and then concatenate it. However, in Python, if you try to concatenate string and int using + operator, you will get a runtime error.

Python Concatenate String and int

Let’s look at a simple example to concatenate string and int using + operator.

s = 'Year is '

y = 2018

print(s + y)

Output:

Traceback (most recent call last):
  File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/strings/string_concat_int.py", line 5, in 
    print(s + y)
TypeError: can only concatenate str (not "int") to str

So how to concatenate string and int in Python? There are various other ways to perform this operation.

Using str() function

The easiest way is to convert int to a string using str() function.

print(s + str(y))

Output: Year is 2018

Using % Operator

print("%s%s" % (s, y))

Using format() function

We can use string format() function too for concatenation of string and int.

print("{}{}".format(s, y))

Using f-strings

If you are using Python 3.6 or higher versions, you can use f-strings too.

print(f'{s}{y}')

You can checkout complete python script and more Python examples from our GitHub Repository.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.

Sign up

I want to create a string using an 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?

Append an int to string python

asked May 17, 2010 at 7:52

6

NOTE:

The method used in this answer (backticks) is deprecated in later versions of Python 2, and removed in Python 3. Use the str() function instead.


You can use:

string = 'string'
for i in range(11):
    string +=`i`
print string

It will print string012345678910.

To get string0, string1 ..... string10 you can use this as YOU suggested:

>>> string = "string"
>>> [string+`i` for i in range(11)]

For Python 3

You can use:

string = 'string'
for i in range(11):
    string += str(i)
print string

It will print string012345678910.

To get string0, string1 ..... string10, you can use this as YOU suggested:

>>> string = "string"
>>> [string+str(i) for i in range(11)]

Append an int to string python

answered Aug 21, 2013 at 17:45

8

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']

answered May 17, 2010 at 7:53

Append an int to string python

YOUYOU

116k32 gold badges184 silver badges216 bronze badges

5

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

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

Append an int to string python

answered May 17, 2010 at 7:53

Rizwan KassimRizwan Kassim

7,6993 gold badges23 silver badges34 bronze badges

0

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

answered May 17, 2010 at 7:53

2

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

You did (range[1,10]):

  • 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.

Append an int to string python

answered May 17, 2010 at 8:17

Tim PietzckerTim Pietzcker

317k56 gold badges491 silver badges548 bronze badges

1

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)) + ']'

Append an int to string python

answered Jul 3, 2015 at 3:01

0

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

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

If we want a list of string values then use the 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.

Append an int to string python

answered Jan 5, 2015 at 9:10

Vivek SableVivek Sable

9,4563 gold badges36 silver badges51 bronze badges

1

I did something else.

I wanted to replace a word, in lists of lists, that contained phrases.

I wanted to replace that string / 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

Append an int to string python

answered Apr 29, 2016 at 14:20

Append an int to string python

Concatenation of a string and integer is simple: just use

abhishek+str(2)

answered Apr 1, 2016 at 9:34

Append an int to string python

HiroHiro

2,8521 gold badge14 silver badges9 bronze badges

1

Not the answer you're looking for? Browse other questions tagged python string integer concatenation or ask your own question.

How do I append an int to a string?

To concatenate a string to an int value, use the concatenation operator. Here is our int. int val = 3; Now, to concatenate a string, you need to declare a string and use the + operator.

Can we add int and string in Python?

You can't add a str and an int. But you can turn a number into a string if you use the str() function.

Can we convert int to string in Python?

In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string.

How do you concatenate inputs in Python?

Python String Concatenation can be done using various ways..
Using + operator..
Using join() method..
Using % operator..
Using format() function..
Using f-string (Literal String Interpolation).