0

I have a query which returns user security settings for specific applications within our bigger app.

The people who setup the table made all of the security settings fit into one field rather than defining the individual fields so I wind up with a blob that looks like this:

NNYYNYNN NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNYNNNNY

Each of those correspond to individual settings. I know how to use string slicing, to get individual fields.

What I would like to know is if I return this blob, is there a way to get say the 15, 25, and 48 characters? I could also setup queries to do substr() and get the characters I want, I am just wondering if there is a python way to do this. I would prefer to not have to setup multiple queries since the variations are literally endless, for the example above which is one of about 20 different applications I have to work with.

1
  • The character at the fifteenth position of string s is accessed as s[14]. Is that not what you want? Commented Oct 16, 2015 at 20:55

2 Answers 2

2

You could use namedtuples to give your security policy named values. For example, let's say your string was three characters, with each position having the meaning read, write, execute. Further, I assume your string of Y and N means yes and no respectively. You could therefore do something like this:

from collections import namedtuple
Security = namedtuple('Security', ['read','write','execute'])
policy_string = 'YYN'   # read = Yes, write = Yes, execute = No
policy = Security(*[c for c in policy_string])
print policy

Which would print

Security(read='Y', write='N', execute='N')

You could then access each setting either by index OR by symbolic name. For example:

>>> policy[0]
'Y'
>>> policy.read
'Y'

Obviously you'd adapt this example with textual descriptions of all 48 security policies.

https://docs.python.org/2.7/library/collections.html#collections.namedtuple

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

Comments

2

For quick extraction you can do something like this:

a, b, c = your_str[14], your_str[24], your_str[47]

or you can write a function:

def get_bits(settings, indices):
    return [settings[i] for i in indices]

3 Comments

Better make that a, b, c = your_str[14], your_str[24], your_str[47] if you want the 15th, 25th, and 48th characters. You are using 1-based indexing; Python is not.
I meant 15-th char starting from 0, but I can fix it if you want.
Thanks ya'all I will take a look at this give it a go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.