Home > database >  Why do we need the colon (:) in the line string = string[:j] ' ' string[j 1:];
Why do we need the colon (:) in the line string = string[:j] ' ' string[j 1:];

Time:08-07

I am trying to understand why do we need the colon if I remove I get an error. I am trying to understand more about strings


string = "welcome to the world of python programming";
    
print("Duplicate characters in a given string: ");  
for i in range(0, len(string)):  
    count = 1;  
    for j in range(i 1, len(string)):  
        if(string[i] == string[j] and string[i] != ' '):  
            count = count   1;  
            string = string[:j]   ' '   string[j 1:];  
    
    if(count > 1 and string[i] != '0'):  
        print(string[i]," - ",count)

CodePudding user response:

It's because they mean very different things. This is just Python syntax.

string[j] says "give me the one letter at index j".

string[:j] says "give me all of the letters up to but not including index j".

string[j:] says "give me all of the letters starting with index j".

This is called "slicing". There are other options as well.

  • Related