简体   繁体   中英

How to split string before and after certain characters?

I have an assignment to create a python program that will receive an IP address and check if its valid or not, my problem is I dont know how to split the input so I will be able to check each octet whether its between 0 - 255 or not?

You want to use the "split()" method.

ip = "192.68.10.10"

ip_arr = ip.split(".")

print(ip_arr)

This will return an array containing the 4 numbers:

['192', '68', '10', '10']

You can then loop through the array to check if each value is under 256. (Don't forget to convert to int before checking)

Don't parse it. There's already a much more powerful library for that. From this answer:

import socket

try:
    socket.inet_aton(addr)
    # legal
except socket.error:
    # Not legal

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM