Category: Python String functions

  • Python String isidentifier() Method

    Python isidentifier() method is used to check whether a string is a valid identifier or not. It returns True if the string is a valid identifier otherwise returns False.

    Python language has own identifier definition which is used by this method.

    Syntax of Python String isidentifier() Method

    It has the following syntax:

    isidentifier()  

    Parameters

    No parameter is required.

    Return

    It returns either True or False.

    Different Examples for Python String isidentifier() Method

    Let’s see some examples of isidentifier() method to understand it’s functionalities.

    Example 1

    A simple Example to apply isidentifier() method, it returns True. See the example.

    # Python isidentifier() method example  
    
    # Variable declaration  
    
    str = "abcdef"  
    
    # Calling function  
    
    str2 = str.isidentifier()  
    
    # Displaying result  
    
    print(str2)

    Output:

    True
    

    Example 2

    Here, we have created variety of identifiers. Some returns True and some False. See the example below.

    # Python isidentifier() method example  
    
    # Variable declaration  
    
    str = "abcdef"  
    
    str2 = "20xyz"  
    
    str3 = "$abra"  
    
    # Calling function  
    
    str4 = str.isidentifier()  
    
    str5 = str2.isidentifier()  
    
    str6 = str3.isidentifier()  
    
    # Displaying result  
    
    print(str4)  
    
    print(str5)  
    
    print(str6)

    Output:

    True
    False
    False
    

    Example 3

    This method is useful in decision making therfore can be used with if statement.

    # Python isidentifier() method example  
    
    # Variable declaration  
    
    str = "abcdef"  
    
    # Calling function  
    
    if str.isidentifier() == True:  
    
        print("It is an identifier")  
    
    else:  
    
        print("It is not identifier")  
    
    str2 = "$xyz"  
    
    if str2.isidentifier() == True:  
    
        print("It is an identifier")  
    
    else:  
    
        print("It is not identifier")
  • Python String isdigit() Method

    Python isdigit() method returns True if all the characters in the string are digits. It returns False if no character is digit in the string.

    Python String isdigit() Method Syntax

    It has the following syntax:

    isdigit()  

    Parameters

    No parameter is required.

    Return

    It returns either True or False.

    Different Examples for Python String isdigit() Method

    Let’s see some examples of isdigit() method to understand it’s functionalities.

    Example 1

    A simple example of digit testing using isdigit() method.

    # Python isdigit() method example  
    
    # Variable declaration  
    
    str = '12345'  
    
    # Calling function  
    
    str2 = str.isdigit()  
    
    # Displaying result  
    
    print(str2)

    Output:

    True
    

    Example 2

    It returns true only if all the characters are digit. See the example below.

    # Python isdigit() method example  
    
    # Variable declaration  
    
    str = "12345"  
    
    str3 = "120-2569-854"  
    
    # Calling function  
    
    str2 = str.isdigit()  
    
    str4 = str3.isdigit()  
    
    # Displaying result  
    
    print(str2)  
    
    print(str4)

    Output:

    True
    False
    

    Example 3

    We can use it in programming to check whether a string contains digits or not.

    # Python isdigit() method example  
    
    # Variable declaration  
    
    str = "123!@#$"  
    
    if str.isdigit() == True:  
    
        print("String is digit")  
    
    else:  
    
        print("String is not digit")

    Output:

    String is not digit
  • Python String isdecimal() Method

    Python isdecimal() method checks whether all the characters in the string are decimal or not. Decimal characters are those have base 10.

    This method returns boolean either true or false.

    Syntax of Python String isdecimal() Method

    It has the following syntax:

    isdecimal()  

    Parameters

    No parameter is required.

    Return

    It returns either True or False.

    Different Examples for isdecimal() Method in Python

    Let’s see some examples of isdecimal() method to understand it’s functionalities.

    Example 1

    A simple example of isdecimal() method to check whether the string contains decimal value.

    # Python isdecimal() method example  
    
    # Variable declaration  
    
    str = "Javatpoint"  
    
    # Calling function  
    
    str2 = str.isdecimal()  
    
    # Displaying result  
    
    print(str2)

    Output:

    False
    

    Example 2

    Let’s try to check floating value and see the outcome. It will return False if string is not decimal.

    # Python isdecimal() method example  
    
    # Variable declaration  
    
    str = "123"     # True  
    
    str3 = "2.50"   # False  
    
    # Calling function  
    
    str2 = str.isdecimal()  
    
    str4 = str3.isdecimal()  
    
    # Displaying result  
    
    print(str2)  
    
    print(str4)

    Output:

    True
    False
    

    Example 3

    Here, we are checking special chars also.

    # Python isdecimal() method example  
    
    # Variable declaration  
    
    str = "123"     # True  
    
    str3 = "@#$"   # False  
    
    # Calling function  
    
    str2 = str.isdecimal()  
    
    str4 = str3.isdecimal()  
    
    # Displaying result  
    
    print(str2)  
    
    print(str4)

    Output:

    True
    False
  • Python String isalpha() Method

    Python isalpha() method returns true if all characters in the string are alphabetic. It returns False if the characters are not alphabetic. It returns either True or False.

    Syntax of Python String isalpha() Method

    It has the following syntax:

    isalpha()  

    Parameters

    No parameter is required.

    Return

    It returns either True or False.

    Different Examples for isalpha() Method in Python

    Let’s see some examples of isalpha() method to understand it’s functionalities.

    Example 1

    Let us take an example to demonstrate the isalpha() Method in Python.

    # Python isalpha() method example  
    
    # Variable declaration  
    
    str = "Javatpoint"  
    
    # Calling function  
    
    str2 = str.isalpha()  
    
    # Displaying result  
    
    print(str2)

    Output:

    True
    

    Example 2

    Let us take another example to demonstrate the isalpha() Method in Python.

    # Python isalpha() method example  
    
    # Variable declaration  
    
    str = "Welcome to the Javatpoint"  
    
    # Calling function  
    
    str2 = str.isalpha()  
    
    # Displaying result  
    
    print(str2)

    Output:

    False
    

    Example 3

    Here, we are going to demonstrate the working of isalpha() Method in Python.

    # Python isalpha() method example  
    
    # Variable declaration  
    
    str = "Javatpoint"  
    
    if str.isalpha() == True:  
    
        print("String contains alphabets")  
    
    else: print("Stringn contains other chars too.")

    Output:

    String contains alphabets
  • Python String isalnum() Method

    Python isalnum() method checks whether the all characters of the string is alphanumeric or not. A character which is either a letter or a number is known as alphanumeric. It does not allow special chars even spaces.

    Syntax of String isalnum() Method

    It has the following syntax:

    isalnum()  

    Parameters

    No parameter is required.

    Return

    It returns either True or False.

    Different Examples for Python String isalnum() Method

    Let’s see some examples of isalnum() method to understand it’s functionalities.

    Example 1

    Let us take an example to demonstrate the Python string isalnum() function in Java.

     # Python isalnum() function example  
    
    # Variable declaration  
    
    str = "Welcome"  
    
    # Calling function  
    
    str2 = str.isalnum()  
    
    # Displaying result  
    
    print(str2)

      Output:

      True
      

      Example 2

      If there is a space anywhere in the string, it returns False. See the example below.

      # Python isalnum() function example  
      
      # Variable declaration  
      
      str = "Welcome"  
      
      # Calling function  
      
      str2 = str.isalnum()  
      
      # Displaying result  
      
      print(str2)

      Output:

      False
      

      Example 3

      Let us take an example to demonstrate the Python string isalnum() function in Java.

      # Python isalnum() function example  
      
      # Variable declaration  
      
      str = "Welcome123" # True  
      
      str3 = "Welcome 123" # False  
      
      # Calling function  
      
      str2 = str.isalnum()  
      
      str4 = str3.isalnum()  
      
      # Displaying result  
      
      print(str2)  
      
      print(str4)

      Output:

      True
      False
      

      Example 4

      It returns True even the string is full of digits. See the example.

      # Python isalnum() function example  
      
      # Variable declaration  
      
      str = "123456"  
      
      # Calling function  
      
      str2 = str.isalnum()  
      
      # Displaying result  
      
      print(str2)

      Output:

      True
      

      Note: This method returns True if any one of these isalpha(), isdecimal(), isdigit(), or isnumeric() returns True.

    1. Python String index() Method

      Python index() method is same as the find() method except it returns error on failure. This method returns index of first occurred substring and an error if there is no match found.

      Signature

      index(sub[, start[, end]])  

      Parameters

      • sub : substring
      • start : start index a range
      • end : last index of the range

      Return Type

      If found it returns an index of the substring, otherwise an error ValueError.

      Let’s see some examples to understand the index() method.

      Python String index() Method Example 1

      # Python index() function example  
      
      # Variable declaration  
      
      str = "Welcome to the Javatpoint."  
      
      # Calling function  
      
      str2 = str.index("at")  
      
      # Displaying result  
      
      print(str2)

      Output:

      18
      

      Python String index() Method Example 2

      An error is thrown if the substring is not found.

      # Python index() function example  
      
      # Variable declaration  
      
      str = "Welcome to the Javatpoint."  
      
      # Calling function  
      
      str2 = str.index("ate")  
      
      # Displaying result  
      
      print(str2)

      Output:

      ValueError: substring not found
      

      Python String index() Method Example 3

      We can also pass start and end index as parameters to make process more customized.

      # Python index() function example  
      
      # Variable declaration  
      
      str = "Welcome to the Javatpoint."  
      
      # Calling function  
      
      str2 = str.index("p",19,21)  
      
      # Displaying result  
      
      print("p is present at :",str2,"index")

      Output:

      p is present at : 20 index
    2. Python String format() Method

      Python is a versatile programming language that is utilized extensively in a wide range of fields, including data analysis and manipulation. Proficiently designing information is significant for introducing data in an unmistakable and significant manner. We’ll look at Python’s powerful format() method, which lets developers format and customize data output, in this article. Your Python programming abilities can be greatly enhanced by effectively using format().

      Python String format() Method Syntax

      It has the following syntax:

      format(*args, **kwargs)  

      Parameters

      • *args: substring
      • **kwargs: start index a range

      Return Type

      It returns a formatted string.

      format() Method

      An adaptable and effective method for organizing strings is provided by Python’s configuration() strategy, an underlying capability. You can control how values in placeholders within a string are displayed. The format() method’s straightforward but effective syntax uses curly braces () as placeholders that can be replaced with values or expressions.

      Simple Formatting:

      A string with one or more placeholders is needed to begin using the format() method. Placeholders are set apart by wavy supports, with discretionary positional or named contentions inside. An elementary illustration:

      name = "John"  
      
      age = 30  
      
      formatted_string = "My name is {} and I'm {} years old.".format(name, age)  
      
      print(formatted_string)

      Output:

      My name is John and I'm 30 years old.
      

      The corresponding values supplied to the format() method take the place of the placeholders in the string in the preceding example. This makes it possible to generate dynamic content using variable values.

      Positional and Named Arguments:

      The configuration() strategy upholds both positional and named contentions, giving you adaptability by the way you give values. Named arguments are assigned based on their names, while positional arguments are filled in the order they appear in the format() method. Take for instance the following:

      product = "Phone"  
      
      price = 999.99  
      
      formatted_string = "The {0} costs ${1:.2f}".format(product, price)  
      
      print(formatted_string)

      Output:

      The Phone costs $999.99
      

      The positional placeholders “0” and “1” in this example correspond to the order of the arguments passed to the format() method. The : .2f inside the subsequent placeholder guarantees that the cost is shown with two decimal spots.

      Conclusion

      The format() method in Python provides a powerful tool for formatting data output. By utilizing placeholders, positional and named arguments, and various formatting options, you can tailor your output to meet specific requirements. Mastering the format() method enhances the readability and aesthetics of your code, making it easier to present data in a clear and organized manner. Harness the potential of format() to unlock new possibilities in your Python programming journey.

    3. Python String find() Method

      First of all, let’s Revise what String is in Python:

      A string is a collection of characters that Python defines as contained in one two or three quotation marks. It is a line of Unicode characters with set lengths. This means that after a string has been created you can not change its value.

      In Python, you can show text numbers symbols and other forms of data using strings. They are frequently used to store and modify textual material read and write files manage user input, and produce output in a certain format.

      Concatenation slicing and indexing are just a few of the operations Python strings can do. Texts may also be changed and edited using various built-in string techniques, such as character replacement, case conversions to uppercase or lowercase, or substring.

      Ex:

      my_string = "Hello, world!"  

      Many different functions are used to modify strings or to operate with Strings.

      One of them is the find() method.

      find() Function in String

      Python finds () method finds a substring in the whole String and returns the index of the first match. It returns -1 if the substring does not match.

      Python String find() Function Syntax:

      The syntax of the find() method is as follows:

      string.find(substring, start, end)  

      Parameters:

      Where:

      • String is the String in which you want to search for the substring
      • Substring is the String you want to search for
      • Start is the index from which the search should begin (optional, defaults to 0)
      • End is the index at which the search should end (optional, defaults to the end of the String)

      Return Type:

      The find() method returns the index of the first occurrence of that substring in the given range. In case the substring is not found, it returns -1.

      Different Examples for Python String find() Function

      Here’s an example of using the find() method to search for a substring within a string:

      Example 1:

      Let us take a program to find a substring in a string using find() Function in Python.

      string = "Hello, world!"  
      
      substring = "world"  
      
      index = string.find(substring)  
      
      print(index)

      Output:

      7
      

      Example 2:

      Finding a substring in a string with start and end indices:

      string = "Hello, world!"  
      
      substring = "l"  
      
      start = 3  
      
      end = 8  
      
      index = string.find(substring, start, end)  
      
      print(index)

      Output:

      3
      

      Example 3:

      How to find a substring that is not present in a string:

      string = "Hello, world!"  
      
      substring = "python"  
      
      index = string.find(substring)  
      
      print(index)

      Output:

      -1
      

      Example 4:

      Finding a substring in a string with multiple occurrences:

      string = "Hello, world!"  
      
      substring = "l"  
      
      index = string.find(substring)  
      
      while index != -1:  
      
          print(index)  
      
          index = string.find(substring, index + 1)

      Output:

      2
      3
      10
    4. Python String expandtabs() Method

      Python expandstabs() method replaces all the characters by sepecified spaces. By default a single tab expands to 8 spaces which can be overridden according to the requirement.

      We can pass 1, 2, 4 and more to the method which will replace tab by the these number of space characters.

      Python String expandtabs() Method Syntax

      It has the following syntax:

      expandtabs(tabsize=8)  

      Parameters

      • tabsize: It is optional and default value is 8.

      Return Type

      It returns a modified string.

      Different Examples for Python String expandtabs() Method

      Let’s see some examples to understand the expandtabs() method.

      Python String expandtabs() Method Example 1

      Calling method without specifying spaces. It sets to it’s default value.

      # Python endswith() function example  
      
      # Variable declaration  
      
      str = "Welcome \t to \t the \t Pythonapp."  
      
      # Calling function  
      
      str2 = str.expandtabs()  
      
      # Displaying result  
      
      print(str2)

      Output:

      Welcome to the Pythonapp.
      

      Python String expandtabs() Method Example 2

      See, how the output is changing after each call. Each method is set to different-different number of spaces.

      # Python endswith() function example  
      
      # Variable declaration  
      
      str = "Welcome \t to \t the \t Pythonapp."  
      
      # Calling function  
      
      str2 = str.expandtabs(1)  
      
      str3 = str.expandtabs(2)  
      
      str4 = str.expandtabs(4)  
      
      # Displaying result  
      
      print(str2)  
      
      print(str3)  
      
      print(str4)

      Output:

      Welcome to the Pythonapp.
      Welcome to the Pythonapp.
      Welcome to the Pythonapp.
    5. Python String endswith() Method

      Python endswith() method returns true of the string ends with the specified substring, otherwise returns false.

      Python String endswith() Method Syntax

      It has the following syntax:

      endswith(suffix[, start[, end]])  

      Parameters

      • suffix : a substring
      • start : start index of a range
      • end : last index of the range

      Start and end both parameters are optional.

      Return Type

      It returns a boolean value either True or False.

      Different Examples for Python String endswith() Method

      Let’s see some examples to understand the endswith() method.

      Python String endswith() Method Example 1

      A simple example which returns true because it ends with dot (.).

      # Python endswith() function example  
      
      # Variable declaration  
      
      str = "Hello this is pythonapp."  
      
      isends = str.endswith(".")  
      
      # Displaying result  
      
      print(isends)

      Output:

      True
      

      Python String endswith() Method Example 2

      It returns false because string does not end with is.

      # Python endswith() function example  
      
      # Variable declaration  
      
      str = "Hello this is pythonapp."  
      
      isends = str.endswith("is")  
      
      # Displaying result  
      
      print(isends)

      Output:

      False
      

      Python String endswith() Method Example 3

      Here, we are providing start index of the range from where method starts searching.

      # Python endswith() function example  
      
      # Variable declaration  
      
      str = "Hello this is pythonapp."  
      
      isends = str.endswith("is",10)  
      
      # Displaying result  
      
      print(isends)

      Output:

      False
      

      Python String endswith() Method Example 4

      It returns true because third parameter stopped the method at index 13.

      # Python endswith() function example  
      
      # Variable declaration  
      
      str = "Hello this is pythonapp."  
      
      isends = str.endswith("is",0,13)  
      
      # Displaying result  
      
      print(isends)

      Output:

      True