Slicing Strings:
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
** Get the characters from position 2 to position 5 (not included):**
b = "Hello, World!"
print(b[2:5])
Output : llo
Slice From the Start
By leaving out the start index, the range will start at the first character:
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[:5])
Output = Hello
Negative Indexing
Use negative indexes to start the slice from the end of the string:
**Get the characters:
From: "o" in "World!" (position -5)
To, but not included: "d" in "World!" (position -2):**
`b = "Hello, World!"
print(b[-5:-2])
Output =orl`
Python - Modify Strings
The upper() method returns the string in upper case
a = "Hello, World!"
print(a.upper())
Output =HELLO, WORLD!
The lower() method returns the string in lower case:
The lower() method returns the string in lower case:
`a = "Hello, World!"
print(a.lower())
Output) =hello, world!`
The strip() method removes any whitespace from the beginning or the end:
`a = " Hello, World! "
print(a.strip())
Output =Hello, World!`
Replace String
Example
The replace() method replaces a string with another string:
`a = "Hello, World!"
print(a.replace("H", "J"))
Output =Jello, World!`
Split String
The split() method returns a list where the text between the specified separator becomes the list items.
Example
The split() method splits the string into substrings if it finds instances of the separator:
'a = "Hello, World!"
print(a.split(","))
['Hello', ' World!']
Output =['Hello', ' World!']'
`Indexing :
fruits = ['apple', 'banana', 'cherry']
x = fruits.index("cherry")
print(x)
Output =2`
The above is the detailed content of trings Indexing & Slicing. For more information, please follow other related articles on the PHP Chinese website!