简体   繁体   中英

How to Concatenate an Index in a String to Another String in Python

I have a string of length for example 20

I want to go in a loop to concatenate a the last 6 characters in the string

I'm doing it like this:

leng = len(theString)

leng2 = leng -6

for i in range(leng2, leng)

      a += theString.index(i)

print a

But i'm getting an error in " a += theString.index(i) "

stating "TypeError: expected a character buffer object"

To get the character of a string a at index i you want to do a[i] . However, if I'm understanding the problem correctly, there is an easier way to do what you want.

You can slice the last 6 characters of a string, a like so:

a[-6:]

This will give you a 6-character string (assuming a has that many characters.)

So to concatenate the last 6 characters of a string to itself, you can do

a += a[-6:]

ie, you don't need to do this character by character.

You have two string A and B . You want to concatenate last 6 character of B to A . If I am right, then you can do this:

# this is faster way
>>> A = "abcdefg"
>>> B = "0123456789"
>>> A = A + B[-6:]
>>> A
'abcdefg456789'

If you want to iterate through your string B to concatenate, then

>>> l = len(B)-6;
>>> for i in range(l,len(B)):
        A = A + B[i]
>>> A
'abcdefg456789'

index method of the string take substring from the string as a argument. In code you given integer value that why such exception get.

update your code:

>>> for i in range(leng2, leng):
...    a += theString[i]

You can directly get last six character by slice method of the string.

>>> theString = "qazxswedcvfrtgbnhyuj"
>>> theString[-6:]
'bnhyuj'

The argument to theString.index must be a string, so, use

a += theString.index(str(i))

However, your code must be incomplete -- for example, a is never initialized! -- so this fix, while indispensable, won't be sufficient. Please show all the code and an example of what result you would expect for a certain initial value of theString .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM