Python provides several built-in string methods that allow you to manipulate and transform strings. Here are some common string methods:
.upper()
: Converts the string to uppercase..lower()
: Converts the string to lowercase..capitalize()
: Converts the first character of the string to uppercase and the rest to lowercase..title()
: Converts the first character of each word in the string to uppercase..replace(old, new)
: Replaces occurrences of the "old" substring with the "new" substring..strip()
: Removes leading and trailing whitespace from the string..split()
: Splits the string into a list of substrings based on a specified delimiter..join(iterable)
: Joins the elements of an iterable (e.g., list, tuple) into a string using the string as the delimiter.Let's see some examples of using string methods in Python:
# Using .upper()
message = "hello, world!"
print(message.upper())
# Using .lower()
name = "John Doe"
print(name.lower())
# Using .capitalize()
sentence = "python is fun"
print(sentence.capitalize())
# Using .title()
title = "programming in python"
print(title.title())
# Using .replace()
sentence = "I like apples."
new_sentence = sentence.replace("apples", "bananas")
print(new_sentence)
# Using .strip()
text = " Hello, World! "
print(text.strip())
# Using .split()
fruits = "apple, banana, cherry"
fruit_list = fruits.split(", ")
print(fruit_list)
# Using .join()
words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence)
Using string methods in Python allows you to manipulate and transform strings easily, making your code more powerful and versatile.