OneBite.Dev - Coding blog in a bite size

slice a string in python

Code snippet on how to slice a string in python

  example_string = "Hello World"
  sliced_string = example_string[0:5]
  print(sliced_string)

This code begins by creating a string with the phrase ‘Hello World’ and assigning it to the variable ‘example_string’. The next line of code slices the string and assigns it to the variable ‘sliced_string’. The slicing is done by indicating the start and end position of the string. In this particular example the start position is 0, indicating the character at the beginning of the string, and the end position is 5, which is one character ahead of the ending character ‘o’. The slicing begins at the 0th character ‘H’ and ends on the 5th character ‘o’. The last line of code prints the sliced string, which has a value of ‘Hello’.

python