Skip to content Skip to sidebar Skip to footer

Is There Any Strncpy() Equivalent Function In Python?

is there any equivalent function for strncpy() of C in python? I want to replace 6 characters in the second string from the first string. 'wonderful' should be replaced with 'beaut

Solution 1:

I want to replace 6 characters in the second string from the first string

str2 = str1[:6] + str2[6:]

Solution 2:

You don't copy strings in python as they're immutable. You simply reassign them like this:

str2 = str1[:6] + str2[6:]

you also have your destination and source strings mixed up.

Solution 3:

Python strings are immutable, so you cannot modify them like you do in other languages. You have to create a new string and reassign str2:

str2 = str1[:6] + str2[6:]

Solution 4:

You can use bytearray if you want in-place modification(normal strings are immutable):

>>>str1 = bytearray("wonderful")>>>str2 = bytearray("beautiful")
for i in xrange(6):
    str2[i] = str1[i]
...>>>print str2
wonderful

Function:

def strncpy(a, b, ind1, ind2):
    for i in xrange(ind1-1, ind2):
        a[i] = b[i]
...>>>str1 = bytearray("wonderful")>>>str2 = bytearray("beautiful")>>>strncpy(str2, str1, 1, 6)>>>print str2
wonderful

Post a Comment for "Is There Any Strncpy() Equivalent Function In Python?"