String methods

Strings are one of the most commonly used data types in Python, and they come with a variety of built-in methods that allow you to manipulate and transform them. Here are some useful string methods for manipulation:

The ".split()" method splits a string into a list of substrings based on a specified delimiter. By default, it splits on whitespace characters.

text = "Hello, this is a sample text."
words = text.split()  # Splitting by whitespace
print(words)  # Output: ['Hello,', 'this', 'is', 'a', 'sample', 'text.']

You can also specify a custom delimiter:

csv_data = "Alice,Bob,Charlie"
names = csv_data.split(',')  # Splitting by comma
print(names)  # Output: ['Alice', 'Bob', 'Charlie']

The ".join()" method is used to concatenate elements of an iterable (e.g., a list) into a single string using the specified separator.

words = ['Hello,', 'this', 'is', 'a', 'sample', 'text.']
text = ' '.join(words)  # Joining with space separator
print(text)  # Output: "Hello, this is a sample text."

These methods are used to remove leading and trailing whitespace characters from a string.

string = "   Hello, world!   "
stripped_string = string.strip()
print(stripped_string)  # Output: "Hello, world!"

You can also provide a specific set of characters to strip:

string = "----Hello, world!----"
stripped_string = string.strip('-')
print(stripped_string)  # Output: "Hello, world!"

".lstrip()" removes leading whitespace, and ".rstrip()" removes trailing whitespace.

These methods return new strings with all characters in uppercase or lowercase, respectively.

text = "Hello, World!"
uppercase_text = text.upper()
lowercase_text = text.lower()

print(uppercase_text)  # Output: "HELLO, WORLD!"
print(lowercase_text)  # Output: "hello, world!"

The ".replace()" method replaces occurrences of a substring with another substring in a string.

text = "Hello, Alice!"
new_text = text.replace("Alice", "Bob")
print(new_text)  # Output: "Hello, Bob!"

These are just a few examples of the many string methods available in Python. These methods make string manipulation and transformation more efficient and convenient, allowing you to work with text data effectively.