简体   繁体   中英

How to delete string from given data in python(without using any built-in function)?

I have created Insertstring function in this way:

def Insertstring(data,text,pos):
    count = 0
    Str = ""
    for i in data:
        if count==pos:
            Str+=text
        count+=1
        Str+=i      
    return Str

print(InsertStr("abcde","f",0))

It's working in the right way.

Output:

fabcde

I want to create Deletestring function in the same way. (It should return the remaining string)

#pos = Starting index to delete
#length = Length of data to be deleted

def Deletestring(data,pos,length):
    pass

print(InsertStr("abcde",2,3))

Expected Output:

ab

Without any built-ins, you can do just slicing:

def delete_string(data, pos, length):
    return data[:pos] + data[pos+length:]

print(delete_string("abcde", 2, 3))
# ab

String slicing can be done to remove the character(s) from the string - We can remove characters from string by slicing the string into pieces and then joining back those pieces.

We can slice a string using operator [].

stringObject[ start : stop : interval]

It returns a new string object containing parts of given string ie it selects a range from start to stop-1 with given step size ie interval . You can find the details regarding this here .

def Deletestring(data,pos,length):
    return data[:pos] + data[pos+length:]

strObj = "This is a sample string"
pos = 6
length = 5

print("Original String => %s" % (strObj))
print("After Delete at pos %d and length %d => %s" % (pos, length, Deletestring(strObj, pos, length)))

Output:

Original String => This is a sample string
After Delete at pos 6 and length 5 => This iample string

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