"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > trings Indexing & Slicing

trings Indexing & Slicing

Published on 2024-07-30
Browse:365

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`

Release Statement This article is reproduced at: https://dev.to/ranjith_jr_fbf2e375879b08/7strings-indexing-slicing-3pb2?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3