• This topic is empty.
Viewing 1 post (of 1 total)
  • Author
    Posts
  • #3264

    Source: Generated taking help of AI tool

    String Functions in Python: An In-Depth Guide with Examples

    Python provides numerous built-in string functions to manipulate and transform strings efficiently. Below is an in-depth look at some commonly used string functions in Python, along with examples to illustrate how they work.

    1. len()

    The len() function returns the number of characters in a string (i.e., the length of the string).

    Example:

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

    2. lower()

    The lower() method converts all the characters in a string to lowercase.

    Example:

    text = "HELLO, WORLD!"
    lowercase_text = text.lower()
    print(lowercase_text) # Output: "hello, world!"
    

    3. upper()

    The upper() method converts all the characters in a string to uppercase.

    Example:

    text = "hello, world!"
    uppercase_text = text.upper()
    print(uppercase_text) # Output: "HELLO, WORLD!"
    

    4. capitalize()

    The capitalize() method converts the first character of the string to uppercase and all other characters to lowercase.

    Example:

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

    5. title()

    The title() method capitalizes the first letter of every word in a string.

    Example:

    text = "hello, world! welcome to python."
    title_text = text.title()
    print(title_text) # Output: "Hello, World! Welcome To Python."
    

    6. find()

    The find() method searches for a specified substring in the string and returns the index of its first occurrence. If the substring is not found, it returns -1.

    Example:

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

    7. replace()

    The replace() method replaces all occurrences of a specified substring with another substring.

    Example:

    text = "Hello, World!"
    replaced_text = text.replace("World", "Python")
    print(replaced_text) # Output: "Hello, Python!"
    

    8. strip(), lstrip(), and rstrip()

    • strip() removes leading and trailing whitespace or specified characters.
    • lstrip() removes leading (left) whitespace or specified characters.
    • rstrip() removes trailing (right) whitespace or specified characters.

    Example:

    text = " Hello, World! "
    stripped_text = text.strip()
    print(stripped_text) # Output: "Hello, World!"
    
    text = ">>>Hello, World!<<<" lstripped_text = text.lstrip(">")
    rstripped_text = text.rstrip("<")
    print(lstripped_text) # Output: "Hello, World!<<<" print(rstripped_text) # Output: ">>>Hello, World!"
    

    9. split()

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

    Example:

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

    10. join()

    The join() method joins the elements of a list or other iterable into a single string, using a specified separator.

    Example:

    fruits = ['apple', 'banana', 'orange']
    joined_text = ', '.join(fruits)
    print(joined_text) # Output: "apple, banana, orange"
    

    11. startswith() and endswith()

    • startswith() checks if the string starts with a specified substring.
    • endswith() checks if the string ends with a specified substring.

    Example:

    text = "Hello, World!"
    print(text.startswith("Hello")) # Output: True
    print(text.endswith("World!")) # Output: True
    

    12. isalpha(), isdigit(), and isalnum()

    • isalpha() returns True if all characters in the string are alphabetic.
    • isdigit() returns True if all characters in the string are digits.
    • isalnum() returns True if all characters in the string are either alphabetic or digits (alphanumeric).

    Example:

    text = "Hello"
    print(text.isalpha()) # Output: True
    
    text = "12345"
    print(text.isdigit()) # Output: True
    
    text = "Hello123"
    print(text.isalnum()) # Output: True
    

    13. count()

    The count() method returns the number of occurrences of a specified substring within the string.

    Example:

    text = "Hello, World! Hello!"
    count = text.count("Hello")
    print(count) # Output: 2
    

    14. center(), ljust(), and rjust()

    • center() centers the string within a specified width, padding it with spaces or other characters.
    • ljust() left-justifies the string within a specified width, padding it on the right.
    • rjust() right-justifies the string within a specified width, padding it on the left.

    Example:

    text = "Hello"
    centered_text = text.center(10, '*')
    left_justified = text.ljust(10, '-')
    right_justified = text.rjust(10, '-')
    
    print(centered_text) # Output: "**Hello***"
    print(left_justified) # Output: "Hello-----"
    print(right_justified) # Output: "-----Hello"
    

    15. zfill()

    The zfill() method pads the string with zeros on the left until the string reaches a specified length.

    Example:

    text = "42"
    padded_text = text.zfill(5)
    print(padded_text) # Output: "00042"
    

    16. format()

    The format() method allows for string formatting, using placeholders marked by {}. It replaces the placeholders with specified values.

    Example:

    text = "Hello, {}!"
    formatted_text = text.format("Alice")
    print(formatted_text) # Output: "Hello, Alice!"
    

    17. partition() and rpartition()

    • partition() splits the string at the first occurrence of a specified separator into a tuple of three elements: the part before the separator, the separator itself, and the part after it.
    • rpartition() does the same, but splits at the last occurrence of the separator.

    Example:

    text = "apple, banana, orange"
    partitioned_text = text.partition(", ")
    print(partitioned_text) # Output: ('apple', ', ', 'banana, orange')
    
    rpartitioned_text = text.rpartition(", ")
    print(rpartitioned_text) # Output: ('apple, banana', ', ', 'orange')
    

    18. encode() and decode()

    • encode() converts a string into a specified encoding, such as UTF-8.
    • decode() converts an encoded string back into a normal string.

    Example:

    text = "Hello, World!"
    encoded_text = text.encode("utf-8")
    decoded_text = encoded_text.decode("utf-8")
    
    print(encoded_text) # Output: b'Hello, World!'
    print(decoded_text) # Output: "Hello, World!"
    

    Conclusion

    Python provides a wide range of string functions that allow you to perform various operations on strings, from basic manipulations like converting case or splitting and joining strings to more complex operations like formatting, encoding, and justifying text. These functions are powerful tools for developers to handle textual data effectively in different scenarios.

     

Viewing 1 post (of 1 total)
  • You must be logged in to reply to this topic.
Scroll to Top