Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Take in Two Strings and Display the Larger String without Using Built-in Functions in Python Program
When it is required to take two strings and display the larger string without using any built-in function, a counter can be used to get the length of the strings, and if condition can be used to compare their lengths.
Below is the demonstration of the same −
Example
string_1 = "Hi there"
string_2 = "Hi how are ya"
print("The first string is :")
print(string_1)
print("The second string is :")
print(string_2)
count_1 = 0
count_2 = 0
for i in string_1:
count_1 = count_1 + 1
for j in string_2:
count_2 = count_2 + 1
if(count_1 < count_2):
print("The larger string is :")
print(string_2)
elif(count_1 == count_2):
print("Both the strings are equal in length")
else:
print("The larger string is :")
print(string_1)
Output
The first string is : Hi there The second string is : Hi how are ya The larger string is : Hi how are ya
Alternative Approach Using Functions
You can create a reusable function to count string length without built-ins ?
def get_string_length(text):
count = 0
for char in text:
count += 1
return count
def find_larger_string(str1, str2):
len1 = get_string_length(str1)
len2 = get_string_length(str2)
if len1 > len2:
return str1
elif len2 > len1:
return str2
else:
return "Both strings are equal in length"
string_1 = "Hello"
string_2 = "Programming"
result = find_larger_string(string_1, string_2)
print(f"First string: {string_1}")
print(f"Second string: {string_2}")
print(f"Result: {result}")
First string: Hello Second string: Programming Result: Programming
How It Works
Two strings are defined and displayed on the console.
Two counter variables are initialized to 0.
The first string is iterated over and its length is determined by incrementing the counter.
The same is done for the second string as well.
These counts are compared to each other using conditional statements.
Depending on the comparison result, the appropriate output is displayed on the console.
Conclusion
This approach demonstrates how to find the larger string by manually counting characters without using Python's built-in len() function. The method uses simple loops and counters to determine string length and conditional statements for comparison.
