String Manipulation

Python string manipulation utilizing built-in methods.

Python - Strings Manipulation:

String manipulation in Python involves various operations you can perform on strings, such as concatenation, splitting, slicing, replacing, and formatting. Here are some common string manipulation operations in Python:


1. Concatenation:

Combining two or more strings.

py Copy Code
str1 = "Hello"
str2 = "Friend"
concatenated_str = str1 + " " + str2
print(concatenated_str)
Output:
Hello Friend

2. Formatting:

Creating formatted strings using 'format()' method.

py Copy Code
name = "Ayan"
age = 28
formatted_str = "My name is {} and I am {} years old.".format(name, age)
print(formatted_str)
Output:
My name is Ayan and I am 28 years old.

3. Splitting:

Splitting a string into a list of substrings based on a delimiter.

py Copy Code
sentence = "This is a sample sentence."
words = sentence.split(" ")
print(words)
Output:
['This', 'is', 'a', 'sample', 'sentence.']

4. Slicing:

Extracting substrings from a string based on indices.

py Copy Code
text = "Hello, Friend!"
substring = text[7:]  # From index 7 to the end
print(substring)
Output:
Friend!

5. Replacing:

Extracting substrings from a string based on indices.

py Copy Code
text = "I like apples, but I also like bananas."
new_text = text.replace("apples", "oranges")
print(new_text)
Output:
I like oranges, but I also like bananas.

6. Case Conversion:

Convert strings into upper, lower, tittle, and capitalize case.

py Copy Code
text = "Hello, How are you?"
print(text.upper())
print(text.lower())
print(text.title())
print(text.capitalize())
Output:
HELLO, HOW ARE YOU?
hello, how are you?
Hello, How Are You?
Hello, how are you?

7. Stripping:

To remove leading and trailing whitespace from a string.

py Copy Code
s = "      Hello      "
stripped_s = s.strip()
Output:
Hello

Note: These are just a few examples of what you can do with Python string manipulation. Python's string methods are versatile and cover a wide range of tasks, making it convenient for working with text data.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.