Why do we need the colon (:) in the line string = string[:j] + ' ' + string[j+1:];
Question:
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)
Answers:
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.
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)
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.