Open In App

Python – String min() method

Last Updated : 30 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

The min() function in Python is a built-in function that returns the smallest item in an iterable or the smallest of two or more arguments. When applied to strings, it returns the smallest character (based on ASCII values) from the string.

Let’s start with a simple example to understand how min() works with strings:

Python
a = "hello"

smallest_char = min(a)
print(smallest_char)  

Output
e

Explanation:

  • The string "hello" contains the characters: 'h', 'e', 'l', 'l', 'o'.’
  • The min() function finds the smallest character based on ASCII values.
  • The ASCII value of 'e' is smaller than that of 'h', 'l', or 'o', so 'e' is returned.

Syntax of min() method

min(iterable)

Parameters

  • iterable: An iterable object (e.g., a string, list, or tuple) from which the smallest element is to be found.

Return Type

  • Returns the smallest element of the iterable based on their ASCII or natural ordering.
  • Raises a ValueError if the iterable is empty.

Examples of min() method

1. Finding the smallest character in a string

To find the smallest character in a string is the most widely used example of min() method. Let’s see how this works:

Python
a = "python"

smallest = min(a)
print(smallest) 

Output
h

Explanation:

  • The min() function scans through these characters and finds 'h', which has the smallest ASCII value.

2. Using min() with case sensitivity

The min() function is case-sensitive and considers uppercase letters to have lower ASCII values than lowercase letters.

Python
a = "HelloWorld"

smallest = min(a)
print(smallest) 

Output
H

Explanation:

  • The string "HelloWorld" contains both uppercase and lowercase letters.
  • ASCII values: 'H' has an ASCII value of 72, while lowercase letters like 'e' or 'o' have higher ASCII values.
  • Thus, 'H' is returned.

3. Applying min() to substrings

The min() function can also be applied to slices of strings.

Python
s = "PythonProgramming"

# Analyzing "Programming"
smallest = min(s[6:])  

print(smallest) 

Output
P

Explanation:

  • The slice s[6:] extracts the substring "Programming".
  • The smallest character based on ASCII values in "Programming" is 'P'.


Next Article
Article Tags :
Practice Tags :

Similar Reads