比较Python中包含十进制的字符串

时间:2019-05-06 02:46:17

标签: python decimal

我在这里有疑问

如何比较Python中具有字符串+小数的变量。 示例:

a = "2.11.22-abc-def-ghi"

if a == (2.11*) :
print "ok"

我只希望只比较前2个小数点,而不关心其余值。我该怎么办?

谢谢

2 个答案:

答案 0 :(得分:0)

如果要比较字符串的一部分,则始终可以使用语法str[start_index: end_index]对其进行切片,然后对切片进行比较。请注意,start_index是包含性的,而end_index是排除性的。例如

name = "Eric Johnson"
name[0:3] #value of the slice is "Eri" no "Eric".

您可以的话

if a[0:4] == "2.11":
 #stuff next

答案 1 :(得分:0)

Here's the most direct answer to your question, I think...a way to code what your pseudocode is getting at:

a = "2.11.22-abc-def-ghi"

if a.startswith("2.11"):
    print("ok")

If you want to grab the numeric value off the front, turn it into a true number, and use that in a comparison, no matter what the specific value, you could do this:

import re

a = "2.11.22-abc-def-ghi"

m = re.match(r"(\d+\.\d+).*", a)
if m:
    f = float(m.group(1))
    if (f == 2.11):
        print("ok")