String Methods In Python. Topic 10

String method In Python

In Python programming language, there is some built-in method for manipulating the strings. String methods are too useful for some cases. Let’s try some important methods that are mostly needed.

len(): Using this method, we can find the length of the string. It means how many characters are in this string.

text = "Hello, World!"
length = len(text)
print(length)  # Output: 13

lower(): With this method you can convert all the characters into small letters.

text = "Hello, World!"
lower_text = text.lower()
print(lower_text)  # Output: hello, world!

upper(): With this method we can convert all characters into capital letters.

text = "Hello, World!"
upper_text = text.upper()
print(upper_text)  # Output: HELLO, WORLD!

capitalize(): Converts the first character of a string to uppercase, and the rest to lowercase.

text = "hello, world!"
capitalized_text = text.capitalize()
print(capitalized_text)  # Output: Hello, world!

count(): Counts the number of occurrences of a substring in the given string.

text = "apple, banana, cherry, banana"
count_banana = text.count("banana")
print(count_banana)  # Output: 2

find(): Finds the first occurrence of a substring in the given string and returns its index. If not found, it returns -1.

text = "Hello, World!"
index_world = text.find("World")
print(index_world)  # Output: 7

replace(): Replaces occurrences of a specified substring with another string.

text = "Hello, World!"
new_text = text.replace("Hello", "Hi")
print(new_text)  # Output: Hi, World!

split(): Splits a string into a list of substrings based on a specified delimiter (default is space).

text = "apple, banana, cherry"
fruits = text.split(", ")
print(fruits)  # Output: ['apple', 'banana', 'cherry']

If you don’t know much about “String Slicing & Operations on String In Python” just click on read more.

These are the few examples, that use most for sting operations. I hope you understand How to Perform String Operations in Python. If you do not understand this topic just comment below with your email ID, and I will mail back to you.

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog