Built with Tutify.io

    AIStudyLabs

    Python String Methods

    Python String Methods

    We will explore the complete list of string methods available in Python. Python provides a rich set of built-in methods to manipulate and process strings. String in python is used to represent text-based data such as words, sentences, and paragraphs.

    In Python, you can manipulate, combine, and process a string in a variety of ways. Strings are immutable in Python, which means you cannot change their content. However, when you modify a string it creates a new string in memory.

    <a id="h-1-python-string-methods"></a>

    1. Python String Methods

    Below is the complete list of string methods available in Python, along with a brief description of each method.

    | Python String Methods | Description | | --- | --- | | str.split() | Splits a string into a list of substrings. | | str.upper() | Converts the string to uppercase. | | str.isdigit() | Checks if the string consists of digits. | | str.endswith() | Returns True if the string ends with a substring. | | str.replace() | Replaces all occurrences of a substring. | | str.isdecimal() | Checks if a string is decimal characters only. | | str.isnumeric() | Returns True if all characters in the string are numeric characters. | | str.find() | Returns index of first substring occurrence. | | str.rfind() | Returns index of last substring occurrence. | | str.index() | Returns index of first substring occurrence. Raise Value error if not found. | | str.rindex() | Returns index of first substring occurrence. Raise Value error if not found. | | str.capitalize() | Capitalizes the first character of string. | | str.casefold() | Converts a string to lowercase form. | | str.center() | Centers string in specified width. | | str.ljust() | Left-justifies string in specified width. | | str.rjust() | Right-justifies string in specified width. | | str.strip() | Removes leading/trailing whitespaces from string. | | str.lstrip() | Removes leading whitespaces from string. | | str.rstrip() | Removes trailing whitespaces from string. | | str.join() | Joins a list of strings using the string as a separator. | | str.encode() | Encodes the string into a specified encoding format. | | str.format() | Inserts values into string placeholders. | | str.format_map() | Formats the specified values and inserts them inside the string's placeholder using mapping. | | str.maketrans() | Returns a translation table usable for str.translate(). | | str.translate() | Replaces specified characters in the string with the characters specified in the translation table. | | str.count() | Counts the number of substring occurrences in string. | | str.startswith() | Checks if the string starts with specified prefix. | | str.expandtabs() | Replaces tab characters in the string with spaces. | | str.zfill() | Fills string left with zeros to width. | | str.isalnum() | Returns True if a String is Number. |

    <a id="h-1-split-split-the-string"></a>

    1. split() - Split the String

    The split() method returns a list of strings after breaking the original string by a specified separator or delimiter. If no separator is specified, the method returns a list of words split by whitespaces.

    Syntax:

    
    # Syntax
    str.split(sep=None, maxsplit=-1)
    

    Example:

    
    # Example
    text = "I Love AIStudyLabs"
    words = text.split()
    print(words)
    
    # Output
    # ['I', 'Love', 'AIStudyLabs']
    

    <a id="h-2-upper-convert-string-to-uppercase"></a>

    2. upper() - Convert String to Uppercase

    The upper() method is a built-in method in Python that allows you to convert all the characters in a string to uppercase. This method does not modify the original string but instead returns a new string with all characters in uppercase.

    Syntax:

    
    # Syntax
    str.upper()
    

    Example:

    
    # Example
    text_upper = text.upper()
    print(text_upper)
    
    # Output
    # I LOVE aistudylabs
    

    <a id="h-3-capitalize-make-string-capitalize"></a>

    3. capitalize() - Make String Capitalize

    The str.capitalize() is a method in Python that takes a string and returns a copy of the string with the first character capitalized and the rest of the characters in lowercase.

    
    # Example
    capitalized_text = text.capitalize()
    print(capitalized_text)
    
    # Ouptut
    # I love AIStudyLabs
    

    <a id="h-4-casefolde-make-string-lowercase"></a>

    4. casefolde() - Make String Lowercase

    In Python, str.casefold() is a string method that returns a string that has been case-folded. casefold means that the string has been converted to a form suitable for caseless matching.

    
    # Example
    text = "I LoVE spArKByExample"
    lower_case = text.casefold()
    print(lower_case)
    
    # Output:
    # i love sparkbyexample
    

    <a id="h-5-count-find-frequency-in-a-string"></a>

    5. count() - Find Frequency in a String

    The count() method returns the number of times a specific substring occurs in a string.

    Syntax:

    
    # Syntax
    str.count(substring, start, end)
    

    Example:

    
    # Check a substring
    word_count = text.count("Spark")
    # Output : 1
    
    # Check a character
    count = text.count('S')
    # Output : 1
    
    # Check in a range
    text.count("h", 2, 10)
    

    <a id="h-6-startswith-check-if-string-starts-with-substring"></a>

    6. startswith() - Check if String Starts with Substring

    To Check if a String starts with a substring, you can use str.startswith. This method is used to check if a string starts with the specified prefix. As can be seen in the following Example, It returns a boolean value indicating whether the original string starts with the prefix.

    Syntax:

    
    # Syntax
    str.startswith(prefix, start=0, end=len(string))
    

    Parameters:

    
    # Example
    print(text.startswith("i")) 
    # Output: True
    print(text.startswith("Love", 7)) 
    # Output: False
    print(text.startswith("Hi")) 
    # Output: False
    

    <a id="h-7-endswith-string-ends-with-substring"></a>

    7. endswith() - String Ends with Substring

    Similarly to the above method, str.endswith() method in Python is used to check if the string ends with the specified suffix or not. The Syntax is similar to the str.startswith(). Remember, these two methods are just the replacement of regular expressions.

    
    # Checking if the string ends with "Examples"
    result = string.endswith("Examples")
    print("String ends with 'Examples': ", result)
    

    <a id="h-8-isdigit-check-if-a-string-is-a-digit"></a>

    8. isdigit() - Check if a String is a Digit

    The str.isdigit() is a method that takes a string as an input and returns True if all the characters in the string are digits, and there is at least one character. If the string has characters other than digits or is empty, it returns False.

    
    # Example
    string = "12345"
    result = string.isdigit()
    print(result)
    # Output: True
    
    string = "12345a"
    result = string.isdigit()
    print(result)
    # Output: False
    

    <a id="h-9-replace-replace-characters-in-a-string"></a>

    9. replace() - Replace Characters in a String

    The str.replace() method is used to replace all occurrences of a specified substring with another substring. Following is the Syntax of this method.

    Syntax:

    
    # Syntax
    String.replace(oldvalue, newvalue, count)
    

    Example:

    
    # Example
    print(text.replace("AIStudyLabs", "Java"))
    # Output
    # I Love Java
    

    <a id="h-10-isdecimal-check-if-a-string-digit-is-decimal"></a>

    10. isdecimal() - Check if a String Digit is Decimal

    The str.isdecimal() method returns a boolean value. If all characters in the string are decimal characters, the method returns True, otherwise it returns False.

    
    # Example
    text = "1234567890"
    print(text.isdecimal()) 
    # Output: True
    
    text = "1234567890abc"
    print(text.isdecimal()) 
    # Output: False
    

    <a id="h-11-isnumeric-check-if-a-string-is-a-numbers"></a>

    11. isnumeric() - Check if a string is a numbers

    This method is used to check if a string consists only of numbers. The str.isnumeric() returns True if indicating all characters in a string are numeric characters. A numeric character is a character for which the is_numeric property in Unicode is True.

    
    # Example
    string = "12345"
    result = string.isnumeric()
    print(result)  
    # True
    
    string = "1234.5"
    result = string.isnumeric()
    print(result)  
    # False
    

    <a id="h-12-find-find-index-of-substring-safe"></a>

    12. find() - Find Index of Substring ( Safe)

    The str.find() method returns the index of the first occurrence of a specified substring in the string. If the substring is not found, it returns -1. It is the replacement of the index() method. This method is more safe then using the index() method.

    Syntax:

    
    # Syntax
    string.find(substring, start, end)
    

    Example:

    
    # Find the index of the first occurrence of the substring 'Love'
    index = string.find('Love')
    
    # Print the result
    print(index)
    

    <a id="h-13-rfind-index-of-last-occurrence-safe"></a>

    13. rfind() - Index of last occurrence ( Safe)

    The str.rfind() method returns the highest index of a substring in a given string, or -1 if the substring is not found. By the highest index we mean the last occurrence of the substring.

    
    # Search for the last occurrence of 'Spark'
    result = string.rfind("Spark")
    print(result)
    # Output: 12
    

    <a id="h-14-index-find-index-of-a-substring"></a>

    14. index() - Find Index of a Substring

    The str.index() method returns the index of the first occurrence of a specified substring in the string. If the substring is not found, it raises a ValueError. It is same is find() except it will raise the ValueError if there is no match.

    Syntax:

    
    # Syntax
    str.index(sub[, start[, end]])
    

    Example:

    
    # Example
    index = sentence.index("Spark")
    print(index)
    # Output: 4
    

    <a id="h-15-rindex-index-of-last-occurrence"></a>

    15. rindex() - Index of Last Occurrence

    Just like the str.rfind(), we can use str.rindex() to returns the last index in the string where substring is found.

    
    # Example
    result = text.rindex("S")
    print(result)
    # Output: 14
    

    <a id="h-16-ljust-left-justify-string"></a>

    16. ljust() - Left-justify String

    This method is used to format and align string values to a specific width, often used in output formatting. It returns a left-justified string of a given width.

    
    # Example
    result = text.ljust(20, '*')
    print("Left-justified text: ", result)
    # Output 
    # Left-justified text: AIStudyLabs********
    

    <a id="h-17-rjust-right-justify-string"></a>

    17. rjust() - Right-justify String

    It works the same way to ljust(), except it fill the string with characters from the right side. The returned string is padded on the left with a specified fill character (default is space) until the desired width is reached.

    
    # Example
    print(text.rjust(20, '*'))
    # Output
    # *******AIStudyLabs
    

    <a id="h-18-strip-remove-whitespaces"></a>

    18. strip() - Remove Whitespaces

    str.strip() is a string method in Python that returns a copy of the string with leading and trailing white space characters removed. It takes an optional set of characters to remove as an argument. If no argument is passed, then white space characters such as spaces, tabs, and newlines are removed. Here's an example:

    
    # Example
    text = "   i Love AIStudyLabs  "
    stripped_text = text.strip()
    print("Stripped Text:", stripped_text)
    # Output
    # Stripped Text: i Love AIStudyLabs
    

    There are two other methods associated with this method. One is lstrip() and the other is rstrip(). Both of them can be used for the same purpose. if you want to remove only the left or right spaces you need to use them correspondingly.

    <a id="h-19-join-concatenate-list-of-strings"></a>

    19. join() - Concatenate List of Strings

    The join() method is used to concatenate a list of strings with a specified separator string. It takes a list of strings as an argument and returns a string that is the concatenation of all the elements in the list, separated by the specified separator.

    
    # Example
    words = ['i', 'Love', 'AIStudyLabs']
    sentence = ' '.join(words)
    print(sentence)
    # Output
    # i Love AIStudyLabs
    

    <a id="h-20-encode-encode-a-string"></a>

    20. encode() - Encode a String

    str.encode() is a method that is used to encode a string into a specific encoding format. This method returns a bytes object.

    Syntax:

    
    # Syntax
    str.encode(encoding='utf-8', errors='strict')
    

    Where,

    
    # Example
    result = text.encode()
    print(result) 
    # b'i Love AIStudyLabs'
    

    <a id="h-21-center-padding-string-with-characters"></a>

    21. center() - Padding String with Characters

    The str.center() returns a centered string of length width. The original string is centered by padding the left and right sides with the specified fillchar (default is space), or truncating the string if it is too long.

    
    # Example
    result = text.center(30, "*")
    print(result)
    # Output
    # ****i Love aistudylabs****
    

    <a id="h-22-zfill-padding-with-zeros"></a>

    22. zfill() - Padding with Zeros

    The str.zfill() is a method that returns a string of length width, where the original string is padded with zeros (0) on the left side to fill up to the desired width. The original string is not modified.

    
    # Example
    text = "123"
    print(text.zfill(5))
    # Output
    # 00123
    

    <a id="h-23-translate-replaced-string-with-character-mappings"></a>

    23. translate() - Replaced String with Character Mappings

    The str.translate() returns a string where specified characters are replaced with their corresponding character mappings as defined in a translation table. The translation table is created using the str.maketrans() method.

    
    # Example
    translate_table = text.maketrans("S", "s")
    s.translate(translate_table)
    'I Love aistudylabs'
    

    <a id="h-24-maketrans-map-characters-in-string"></a>

    24. maketrans() - Map Characters in String

    The str.maketrans() method requires two ASCII string arguments of equal length, and returns a translation table that will map each character in the first argument to its corresponding character in the second argument. This table can be used besides str.translate() method.

    
    # Example
    x = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    y = "abcdefghijklmnopqrstuvwxyz"
    translation_table = str.maketrans(x, y)
    "HELLO".translate(translation_table)
    # Output : 'hello'
    

    <a id="h-25-format-map-format-string-using-mapping"></a>

    25. format_map() - Format String Using Mapping

    It is similar to the str.format() method, but instead of passing positional or keyword arguments, a mapping or dictionary is passed to the method.

    Syntax:

    
    # Syntax
    str.format_map(mapping)
    

    Example:

    
    # Example
    person = {'first_name': 'Ali', 'last_name': 'H'}
    greeting = "Hello, my name is {first_name} {last_name}."
    print(greeting.format_map(person))
    # Output
    # Hello, my name is Ali H.
    

    <a id="h-26-format-format-string"></a>

    26. format() - Format String

    It allows you to format a string by replacing placeholders in the string with values. The placeholders are indicated by curly braces {}.

    
    # Example
    site= "AIStudyLabs"
    time= 5
    
    # Create a formatted string
    formatted_string = "I visit {} for {} hours.".format(site, time)
    print(formatted_string) 
    # Output: 'I visit AIStudyLabs for 5 hours.'
    

    <a id="h-27-isalnum-check-if-string-is-alphanumeric"></a>

    27. isalnum() - Check if String is Alphanumeric

    This method returns True if all characters in a given string are alphanumeric (i.e., either alphabets or numbers), and there is at least one character in the string. It returns False otherwise.

    
    # Example
    text = "Python123"
    print(text.isalnum())  
    # True
    
    text = "Python 123"
    print(text.isalnum())  
    # False
    

    <a id="h-28-expandtabs-replace-tab-characters"></a>

    28. expandtabs() - Replace Tab Characters

    The str.expandtabs() replaces tab characters (\t) in a string with spaces, and returns the expanded string. The number of spaces used per tab character can be specified as an argument.

    Syntax:

    
    # Syntax
    string.expandtabs(tabsize=8)
    

    Example:

    
    # Example
    text = "1\t2\t3"
    result = text.expandtabs()
    print(result) 
    # "1       2       3"
    

    <a id="h-summary-and-conclusion"></a>

    Summary and Conclusion

    We discussed Python String methods with examples. You have learned about the use of each python string method with examples. You now have a clear understanding of working with string methods in Python. Comment below if you have any questions.

    Happy Learning!!!

    <a id="h-related-articles"></a>

    Related Articles