Blog

  • 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
    6. Python String Encode() Method

      Python encode() method encodes the string according to the provided encoding standard. By default Python strings are in unicode form but can be encoded to other standards also. Encoding is a process of converting text from one standard code to another.

      Python String encode() Method Syntax

      It has the following syntax:

      encode(encoding="utf-8", errors="strict")  

      Parameters

      • encoding : encoding standard, default is UTF-8
      • errors : errors mode to ignore or replace the error messages.

      Both are optional. Default encoding is UTF-8.

      Error parameter has a default value strict and allows other possible values ‘ignore’, ‘replace’, ‘xmlcharrefreplace’, ‘backslashreplace’ etc too.

      Return Type

      It returns an encoded string.

      Different Examples for Python String Encode() Method 

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

      Python String Encode() Method Example 1

      A simple method which encode unicode string to utf-8 encoding standard.

      # Python encode() function example  
      
      # Variable declaration  
      
      str = "HELLO"  
      
      encode = str.encode()  
      
      # Displaying result  
      
      print("Old value", str)  
      
      print("Encoded value", encode)

      Output:

      Old value HELLO
      Encoded value b 'HELLO'
      

      Python String Encode() Method Example 2

      We are encoding a latin character

      � into default encoding.  
      
      # Python encode() function example  
      
      # Variable declaration  
      
      str = "H�LLO"  
      
      encode = str.encode()  
      
      # Displaying result  
      
      print("Old value", str)  
      
      print("Encoded value", encode)

      Output:

      Old value H�LLO
      Encoded value b'H\xc3\x8bLLO'
      

      Python String Encode() Method Example 3

      We are encoding latin character into ascii, it throws an error. See the example below

      # Python encode() function example  
      
      # Variable declaration  
      
      str = "H�LLO"  
      
      encode = str.encode("ascii")  
      
      # Displaying result  
      
      print("Old value", str)  
      
      print("Encoded value", encode)

      Output:

      UnicodeEncodeError: 'ascii' codec can't encode character '\xcb' in position 1: ordinal not in range(128)
      

      Python String Encode() Method Example 4

      If we want to ignore errors, pass ignore as the second parameter.

      # Python encode() function example  
      
      # Variable declaration  
      
      str = "H�LLO"  
      
      encode = str.encode("ascii","ignore")  
      
      # Displaying result  
      
      print("Old value", str)  
      
      print("Encoded value", encode)

      Output:

      Old value H�LLO
      Encoded value b'HLLO'
      

      Python String Encode() Method Example 5

      It ignores error and replace character with ? mark.

      # Python encode() function example  
      
      # Variable declaration  
      
      str = "H�LLO"  
      
      encode = str.encode("ascii","replace")  
      
      # Displaying result  
      
      print("Old value", str)  
      
      print("Encoded value", encode)

      Output:

      Old value H�LLO
      Encoded value b'H?LLO'
    7. Python String Count() Method

      It returns the number of occurences of substring in the specified range. It takes three parameters, first is a substring, second a start index and third is last index of the range. Start and end both are optional whereas substring is required.

      Python String count() Method Syntax

      It has the following syntax:

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

      Parameters

      • sub (required)
      • start (optional)
      • end (optional)

      Return Type

      It returns number of occurrences of substring in the range.

      Different Examples for Python String count() Method

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

      Python String count() Method Example 1

      Let us take an example to demonstrate the working of the string count() method in Python.

      # Python count() function example  
      
      # Variable declaration  
      
      str = "Hello Pythonapp"  
      
      str2 = str.count('t')  
      
      # Displaying result  
      
      print("occurences:", str2)

      Output:

      occurences: 2
      

      Python String Count() Method Example 2

      Let us take an example to demonstrate the working of the string count() method in Python.

      # Python count() function example  
      
      # Variable declaration  
      
      str = "ab bc ca de ed ad da ab bc ca"  
      
      oc = str.count('a')  
      
      # Displaying result  
      
      print("occurences:", oc)

      Here, we are passing second parameter (start index).

      Python String Count() Method Example 3

      Let us take another example to demonstrate the working of the string count() method in Python.

      # Python count() function example  
      
      # Variable declaration  
      
      str = "ab bc ca de ed ad da ab bc ca"  
      
      oc = str.count('a', 3)  
      
      # Displaying result  
      
      print("occurences:", oc)

      Output:

      occurences: 5
      

      Python String Count() Method Example 4

      The given example is using all three parameters and returning result from the specified range.

      # Python count() function example  
      
      # Variable declaration  
      
      str = "ab bc ca de ed ad da ab bc ca"  
      
      oc = str.count('a', 3, 8)  
      
      # Displaying result  
      
      print("occurences:", oc)

      Output:

      occurences: 1
      

      Python String Count() Method Example 5

      It can count non-alphabet chars also, see the given example.

      # Python count() function example  
      
      # Variable declaration  
      
      str = "ab bc ca de ed ad da ab bc ca 12 23 35 62"  
      
      oc = str.count('2')  
      
      # Displaying result  
      
      print("occurences:", oc)

      Output:

      occurences: 3