Python Language
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.
str1 = "Hello" str2 = "Friend" concatenated_str = str1 + " " + str2 print(concatenated_str)
Hello Friend
2. Formatting:
Creating formatted strings using 'format()' method.
name = "Ayan" age = 28 formatted_str = "My name is {} and I am {} years old.".format(name, age) print(formatted_str)
My name is Ayan and I am 28 years old.
3. Splitting:
Splitting a string into a list of substrings based on a delimiter.
sentence = "This is a sample sentence." words = sentence.split(" ") print(words)
['This', 'is', 'a', 'sample', 'sentence.']
4. Slicing:
Extracting substrings from a string based on indices.
text = "Hello, Friend!" substring = text[7:] # From index 7 to the end print(substring)
Friend!
5. Replacing:
Extracting substrings from a string based on indices.
text = "I like apples, but I also like bananas." new_text = text.replace("apples", "oranges") print(new_text)
I like oranges, but I also like bananas.
6. Case Conversion:
Convert strings into upper, lower, tittle, and capitalize case.
text = "Hello, How are you?" print(text.upper()) print(text.lower()) print(text.title()) print(text.capitalize())
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.
s = " Hello " stripped_s = s.strip()
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 actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.