如何拆分字符串并返回字符串的一部分

时间:2019-03-31 01:14:09

标签: python string split

Python的新手-尝试编写具有用户输入IP地址并返回该地址的前3个八位字节的代码/脚本,因此我可以在其中添加更多文本。

问题是如何返回用户正确输入的3个八位字节。

关于如何实现这一目标的任何想法?

我试图拆分字符串,然后使用join函数返回它,该函数仅在字符串完全匹配时才起作用。因此,10.10.10将返回正确的字符串,但由于我的打印语句,192.1.1将不会正确返回。

ip = input("Please enter an ip address with mask in CIDR format: ")
x = ip.split(".")

if "0/24" in x:
s = "."
s = s.join(x)
print(s[0:9] + "20 - " + s[0:9] + "191 is open range to use.")
    else:
print("something else")

因此,如果用户键入192.10.10.0/24

我希望我的退货声明为:

192.10.10.20 - 192.10.10.191 is open range to use

2 个答案:

答案 0 :(得分:0)

您只是缩进了错误。其他一切正常。 只需使用以下代码:

ip = input("Please enter an ip address with mask in CIDR format: ")
x = ip.split(".")

if "0/24" in x:
    s = "."
    s = s.join(x)
    print(s[0:9] + "20 - " + s[0:9] + "191 is open range to use.")
else:
    print("something else")

答案 1 :(得分:0)

问题是您假设连接的字符串的长度相同,而与输入无关,这显然不是事实。

通过对split的结果进行切片,而不是对连接的字符串进行切片,我们可以确保自己只有前三个八位位组,然后可以然后对其进行添加。另外,如果您使用的Python> = 3.6,则可以使用 f-string 更好地设置文本格式。

ip = input("Please enter an ip address with mask in CIDR format: ")
ip_split = ip.split(".")

if '0/24' in x:
    result = '.'.join(ip_split[:3])
    message = f'{result}.20 - {result}.191 is open range to use.'
    # For Python <= 3.5, use this instead:
    # message = '{result}.20 - {result}.191 is open range to use.'.format(result=result)
    print(message)
else:
    print('something else')

输出:

Please enter an ip address with mask in CIDR format: 192.10.10.0/24
192.10.10.20 - 192.10.10.191 is open range to use.