社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

Python 3:字符串之间的比较

Raisul Islam • 3 年前 • 1454 次点击  

我想知道,

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

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

所以在字符串中,它只比较字符串中的数字。因此,它正在打印“2周大于1个月”。如果我将值从“1个月”增加到“3个月”,则打印“2周小于3个月”。它如何检测自身以进行正确的比较?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130364
 
1454 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Tom
Reply   •   1 楼
Tom    3 年前

这是我的例子,比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}')
vasia
Reply   •   2 楼
vasia    3 年前

首先需要从字符串中获取周数或月数,然后比较这些数字。仅仅通过比较字符串,你就是在按字典顺序比较它们,这并不能提供你想要的东西。获取周数或月数的一种方法:

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}')