Tuesday, July 26, 2022

What are string slices and how to create them?

The string slice is a string segment. When a string is assigned to a variable the string segment or slice can be created using square ([]) brackets. In general, creating a slice of a string can be written as:
variable_name = "string"
slice_var = variable_name[I:J]
In the first command line we assigned the "string" to a variable variable_name. In the second command line, we have created a string slice of a variable_name. Here I and J are arbitrary indices. In the following example, we will split one string of four.
Example 1 Create a script that will split a string:
"This is the first string. This is a second string. This is a third string. This is a fourth string." of four strings.
Solution: First the string will be assigned to a variable named GiantString.
GiantString = "This is the first string.This is a second string.
This is a third string.This is a fourth string."
To check the length of a GiantString variable and print out the value type in the following code.
Glen = len(GianString)
print("Glen = {}".format(Glen))
The output is given below.
Glen = 99
So the Giant string variable has 99 characters including the space character. Splitting the GiantString into four strings will require counting the characters. The range of indices of each string is given below.
firstString = GiantString[0:25]
secondString = GiantString[26:50]
thirdString = GiantString[50:73]
fourthString = GiantString[74:98]
print("first string = {}".format(firstString))
print("second string = {}".format(secondString))
print("third string = {}".format(thirdString))
print("fourth string = {}".format(fourthString))
Output.
first string = This is the first string.
second string = This is a second string.
third string = This is a third string.
fourth string = This is a fourth string
To bypass counting the indexes we can write a simple for loop that will traverse through the GiantString and check for occurrences of uppercase character "T".
indexes = []
for i in range(0,len(GiantString)-1,1):
if GiantString[i].isupper():
indexes.append(i)
else: pass
print("indexes = {}".format(indexes))
Output:
indexes = [0, 25, 49, 72]

No comments:

Post a Comment