Home  >  Article  >  Backend Development  >  trings Indexing & Slicing

trings Indexing & Slicing

WBOY
WBOYOriginal
2024-07-25 00:49:021065browse

trings Indexing & Slicing

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:ython LoopsNext article:ython Loops