blargh
blargh

Reputation: 39

Exchanging characters in a string

I need to exchange the middle character in a numeric string of 15 numbers with the last number of the string.

So I get that this:

def string(str):  
      return str[-1:] + str[1:-1] + str[:1]  

print(string('abcd'))  
print(string('12345')) 

RESULTS:

dbca
52341

But how can I make it so that in the initial input string, 012345678912345,

where the 7 is exchanged with the last character in the string 5?

Upvotes: 0

Views: 197

Answers (4)

Mayank Porwal
Mayank Porwal

Reputation: 34046

You can have a function for this:

    In [178]: def swap_index_values(my_string):
     ...:     l = list(my_string)
     ...:     middleIndex = (len(l) - 1)/2 
     ...:     middle_val = l[middleIndex]
     ...:     l[middleIndex] = l[-1]
     ...:     l[-1] = middle_val
     ...:     return ''.join(l)
     ...: 

    In [179]: 

    In [179]: a
    Out[179]: '012345678912345'

    In [180]: swap_index_values(a)
    Out[180]: '012345658912347'

Above, you can see that middle value and last values have been exchanged.

Upvotes: 1

timgeb
timgeb

Reputation: 78650

Consider

def last_to_mid(s):
    if len(s) == 1:
        return s

    if len(s)%2 == 0:            
        raise ValueError('expected string of odd length')

    idx = len(s)//2
    return f'{s[:idx]}{s[-1]}{s[idx+1:-1]}{s[idx]}'

operating like this:

>>> last_to_mid('021')
'012'
>>> last_to_mid('0123x4567')
'01237456x'
>>> last_to_mid('1')
'1'

Assuming you have Python 3.6 or newer for f-strings.

Upvotes: 1

sandeep
sandeep

Reputation: 21

s1='1243125'
s2=s1[:len(s1)//2] + s1[-1] + s1[len(s1)//2 + 1:]
print(s2)

'1245125'

Upvotes: 0

Christian König
Christian König

Reputation: 3570

In this very specific context (always the middle and last character of a string of length 15), your initial approach can be extended to:

text[0:7]+text[-1]+text[8:-1]+text[7]

Also try to avoid variable names like str, since they shadow the function of the same name.

Upvotes: 0

Related Questions