Python String and Integer concatenation [duplicate

2019-01-01 13:00发布

This question already has an answer here:

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?

9条回答
看淡一切
2楼-- · 2019-01-01 13:06
for i in range[1,10]: 
  string = "string" + str(i)

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

查看更多
情到深处是孤独
3楼-- · 2019-01-01 13:06

Concatenation of a string and integer is simple: just use

abhishek+str(2)
查看更多
永恒的永恒
4楼-- · 2019-01-01 13:07
string = 'string%d' % (i,)
查看更多
浪荡孟婆
5楼-- · 2019-01-01 13:09
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.

查看更多
临风纵饮
6楼-- · 2019-01-01 13:12

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))+']'
查看更多
情到深处是孤独
7楼-- · 2019-01-01 13:14

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
查看更多
登录 后发表回答