0

I have this line

Server:x.x.x.x # U:100 # P:100 # Pre:0810 # Tel:xxxxxxxxxx

and I want to copy the value 0810 which is after Pre: value How i can do that ?

2 Answers 2

1

You could use the re module ('re' stands for regular expressions) This solution assumes that your Pre: field will always have four numbers. If the length of the number varies, you could replace the {4}(expect exactly 4) with + (expect 'one or more')

>>> import re
>>> x = "Server:x.x.x.x # U:100 # P:100 # Pre:0810 # Tel:xxxxxxxxxx"
>>> num = re.findall(r'Pre:(\d{4})', x)[0] # re.findall returns a list

>>> print num
'0810'

You can read about it here:

https://docs.python.org/2/howto/regex.html

Sign up to request clarification or add additional context in comments.

Comments

1

As usual in these cases, the best answer depends upon how your strings will vary, and we only have one example to generalize from.

Anyway, you could use string methods like str.split to get at it directly:

>>> s = "Server:x.x.x.x # U:100 # P:100 # Pre:0810 # Tel:xxxxxxxxxx"
>>> s.split()[6].split(":")[1]
'0810'

But I tend to prefer more general solutions. For example, depending on how the format changes, something like

>>> d = dict(x.split(":") for x in s.split(" # "))
>>> d
{'Pre': '0810', 'P': '100', 'U': '100', 'Tel': 'xxxxxxxxxx', 'Server': 'x.x.x.x'}

which makes a dictionary of all the values, after which you could access any element:

>>> d["Pre"]
'0810'
>>> d["Server"]
'x.x.x.x'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.