Home > Blockchain >  Python 3: Comparison between strings
Python 3: Comparison between strings

Time:03-07

I want to know something like,

weeks = '2 Weeks'
months = '1 Months'

if weeks < months:
    print(f'{weeks} is less than {months}')
else:
    print(f'{weeks} is greater than {months}')

so in the string, it only compares the numbers in the string. So it is printing "2 Weeks is greater than 1 Month". If I increase the value from '1 Month' to '3 Months' it then printing "2 Weeks is less than 3 Months". How can it detect itself to make the correct comparison?

CodePudding user response:

You need to first get the number of weeks, or months, from the string, and then compare the numbers. By just comparing strings, you are comparing them lexicographically, which will not give you what you want. One way to get the number of weeks or months:

weeks = '2 Weeks'
months = '1 Months'

num_weeks = int(weeks.split()[0])
num_months = int(months.split()[0])

if num_weeks < (num_months * 4):
    print(f'{num_weeks} is less than {num_months}')
else:
    print(f'{num_weeks} is greater than {num_months}')

CodePudding user response:

Here is my example, a little bit longer than Vasias :):

week = input('Week: ') # Get the weeks
month = input('Month: ') # Get the months

# Get the numbers in weeks and months
numberWeek = []
numberMonth = []

numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9']

for letter in week:
    for num in numbers:
        if num in letter:
            numberWeek.append(letter)

for letter in month:
    for num in numbers:
        if num in letter:
            numberMonth.append(letter)

numberWeek = ''.join(numberWeek)
numberWeek = int(numberWeek)

numberMonth = ''.join(numberMonth)
numberMonth = int(numberMonth)

# Convert the number of weeks to month
numberWeek = numberWeek / 4

# Output
if numberWeek < numberMonth:
    print(f'{week} is less than {month}')
elif numberWeek > numberMonth:
    print(f'{week} is greater than {month}')
elif numberWeek == numberMonth:
    print(f'{week} is the same as {month}')
  • Related