简体   繁体   中英

How to retrieve the last 5 characters from dictionary value after converting to string

I'm writing a Python script that logs into a server and pulls router data through an api. The pulled data is then used to create a dictionary with router names as the key and a telnet url as the key. Here is an example of the url that's collected.

telnet://192.168.1.113:32769

The telnet port is the last 5 characters of the url and I'm trying to pull that information only. I know with a string I can use (-5) but I'm getting the following error.

 Traceback (most recent call last):
  File "C:\Users\b\Documents\Atom Test1 Project\test_wip.py", line 41, in <module>
    test_value2=test_value.split(-5)
TypeError: must be str or None, not int
[Finished in 1.812s]

I think this means I need to convert it tonto a string. I tried converting and then retrieving the last 5 charcters but it's not working. Here is my code.

from __future__ import unicode_literals, print_function
import eve
import json
import time
from netmiko import ConnectHandler, redispatch
#from resteve import eve

import json
address = '192.168.1.113'
instance = m11.Server(address)
instance.login('admin', 'password', '0')
users = instance.get_all_nodes()
payload = json.loads(users.content)
data = payload['data']

users = instance.get_all_nodes()
payload = json.loads(users.content)
data = payload['data']

for item in payload["data"].values():
    result[item["name"]] = item["url"]
    test_value=item['url']
    print(test_value)
    test_value.format(str)
    test_value2=test_value.split(-5)
    print(test_value2)

I'm new at this and still putting it all together so any help is greatly appreciated. Thanks.

要获得最后 5 个字符,请使用索引test_value[-5:] ,因为.split()需要一个字符串,在这里它将尝试拆分第一个参数

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