user1592380
user1592380

Reputation: 36267

how to concatenate 'str' and 'tuple' objects

I have the following tuple:

out = [1021,1022 ....]  # a tuple

I need to iterate through some records replacing each the numbers in "Keys1029" with the list entry. so that instead of having:

....Settings="Keys1029"/>
....Settings="Keys1029"/>

We have:

....Settings="Keys1020"/>
....Settings="Keys1022"/>

I have the following:

for item in out:
    text = text.replace("Keys1029","Keys"+(str(item),1))

This gives TypeError: cannot concatenate 'str' and 'tuple' objects.

Can someone advise me on how to fix this?

Thanks in advance

Upvotes: 0

Views: 9692

Answers (6)

user803422
user803422

Reputation: 2814

Try this:

for item in out:
    text = text.replace("Keys1029","Keys"+str(item))

I removed the () around str, as (..., 1) makes it a tuple.

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142156

You could use re.sub with a replacement function to do this. So for each matching pattern you take the next item from your out list, and use that as a replacement. Note that you will get an exception thrown if there aren't enough outs, but not the other way around.

An advantage of this approach is that it does the replacements all in one go - so you don't need to do a str.replace for as many items as there are in out.

Also, if you so wanted and it was suitable, you could ditch out as is and use something such as out = itertools.count(1021) and that'd give you an iterable of increasing integers starting with 1021.

example based on OP

out = [1021, 1022]

text=  """
....Settings="Keys1029"/>
....Settings="Keys1029"/>"""

import re
print re.sub('(Settings="Keys)(.*?)(")', lambda m, n=iter(out): m.group(1) + str(next(n)) + m.group(3), text)

Then you end up with:

....Settings="Keys1021"/>
....Settings="Keys1022"/>

Upvotes: 0

Pavel Strakhov
Pavel Strakhov

Reputation: 40502

First of all, [1021,1022 ....] is a list, not a tuple. (1021,1022 ....) would be a tuple.

item is a number, str(item) is a string containing this number. Use "Keys"+str(item) to concatenate two strings. There is no need to create a tuple.

Also you can use formatting method: "Keys%d" % item.

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 113988

text.replace("Keys1029","Keys%s"%item)

should work fine

Upvotes: 0

Andrew Clark
Andrew Clark

Reputation: 208475

You have some unnecessary parentheses, try the following:

for item in out:
    text = text.replace("Keys1029", "Keys"+str(item), 1)

Upvotes: 4

Sukrit Kalra
Sukrit Kalra

Reputation: 34493

"Keys"+(str(item),1)

"Keys" is a string and (str(item), 1) is a tuple. You cannot concatenate them. Try doing.

"Keys"+str(item)

Upvotes: 1

Related Questions