Python 3 – String min() Method
The min()
method in Python is used to find the minimum value among the given arguments. Similarly, in the case of strings, it returns the smallest character according to Unicode.
Syntax
string.min()
Parameters
None.
Return Value
The min()
method returns the smallest character according to Unicode.
Examples
Let’s now look at some examples where min()
method in strings can be used.
Example 1 – Simple String
string = "Hello World!"
print("Min character:", min(string))
Output:
Min character: ' '
The above example returns the smallest character in the string “Hello World!”, which is a space character (” “).
Example 2 – Multiple Strings
string1 = "apple"
string2 = "banana"
string3 = "cherry"
print("Min character:", min(string1, string2, string3))
Output:
Min character: 'a'
The above example returns the smallest character out of “apple”, “banana”, and “cherry”, which is the character “a”.
Example 3 – Case Sensitive Comparison
string = "aAbBcC"
print("Min character:", min(string))
Output:
Min character: 'A'
In this example, we can see that the min()
method compares the characters based on their Unicode value. Hence, the smallest character in the given string “aAbBcC” is ‘A’.
Example 4 – Empty String
string = ""
print("Min character:", min(string))
Output:
ValueError: min() arg is an empty sequence
In the case of an empty string, the min()
method will raise a ValueError
with the message “min() arg is an empty sequence”.
Conclusion
In conclusion, with the min()
method in Python, we can find the smallest character among the given strings. Keep in mind that it compares the characters based on their Unicode values and raises a ValueError
in the case of an empty string. We hope that this article has been useful to you in understanding the min()
method in strings in Python.