Extended Slicing and String Methods

 Extended Slicing

Syntax:

variable[start_index:end_index:step]

Step determines the increment between each index for slicing.

Code

a = "Waterfall"
part = a[1:6:3]
print(part)
PYTHON

Output

ar

Methods

Python has a set of built-in reusable utilities. They simplify the most commonly performed operations are:

String Methods

  • isdigit()
  • strip()
  • lower()
  • upper()
  • startswith()
  • endswith()
  • replace()
     and more...

Isdigit

Syntax:

str_var.isdigit()

Gives

True
if all the characters are digits. Otherwise,
False

Code

is_digit = "4748".isdigit()
print(is_digit)
PYTHON

Output

True

Strip

Syntax:

str_var.strip()

Removes all the leading and trailing spaces from a string.

Code

mobile = " 9876543210 "
mobile = mobile.strip()
print(mobile)
PYTHON

Output

9876543210

Strip - Specific characters

Syntax:

str_var.strip(chars)

We can also specify characters that need to be removed.

Code

name = "Ravi."
name = name.strip(".")
print(name)
PYTHON

Output

Ravi

Strip - Multiple Characters

Removes all spaces, comma(,) and full stop(.) that lead or trail the string.

Code

name = ", .. ,, ravi ,, .. ."
name = name.strip(" ,.")
print(name)
PYTHON

Output

ravi

Replace

Syntax:

str_var.replace(old,new)

Gives a new string after replacing all the occurrences of the old substring with the new substring.

Code

sentence = "teh cat and teh dog"
sentence = sentence.replace("teh","the")
print(sentence)
PYTHON

Output

the cat and the dog

Startswith

Syntax:

str_var.startswith(value)

Gives

True
if the string starts with the specified value. Otherwise,
False

Code

url = "https://onthegomodel.com"
is_secure_url = url.startswith("https://")
print(is_secure_url)
PYTHON

Output

True

Endswith

Syntax:

str_var.endswith(value)

Gives

True
if the string ends with the specified value. Otherwise,
False

Code

gmail_id = "rahul123@gmail.com"
is_gmail = gmail_id.endswith("@gmail.com")
print(is_gmail)
PYTHON

Output

True

Upper

Syntax:

str_var.upper()

Gives a new string by converting each character of the given string to uppercase.

Code

name = "ravi"
print(name.upper())
PYTHON

Output

RAVI

Lower

Syntax:

str_var.lower()

Gives a new string by converting each character of the given string to lowercase.

Code

name = "RAVI"
print(name.lower())
PYTHON

Output

ravi

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form