prepare command and use startswith option with string - python-3.x

I am receiving some rule from file and would like to prepare query at run time but getting following error. any input.
a = "AC"
cond = "startswith"
rule = "AC"
eval("%s.%s(%s)" %(a, cond, rule))

Try in this way:
eval(("'%s'.%s('%s')" %(a, cond, rule)))
You forgot single quotes to define strings in function evaluation

If you must use eval, use %r in your format string when you want to substitute in strings, to get the repr of the str (including quotes) so they remain valid string literals, not raw names; as written, you're trying to run the code AC.startswith(AC), with %r for first and third placeholder (eval("%r.%s(%r)" %(a, cond, rule))) you'd be running "AC".startswith("AC").

Related

How to get demangled function name using regex

I have list of demangled-function names like _Z6__comp7StudentS_
_Z4SortiSt6vectorI7StudentSaIS0_EE. I read wiki and found out that it follows some sort of defined structure. _Z is mangled Symbol followed by a number and then the function name of that length.
So I wanted to retrieve that function name using regex. I only come close to _Z(?:\d)(?<function_name>[a-z_A-Z]){\1}. But referring \1 won't work because its string, right? Is there a single regex pattern solution to this.
You can use 2 capture groups, and get the part of the string using the position of capture group 2
import re
pattern = r"_Z(\d+)([a-z_A-Z]+)"
s = "_Z4SortiSt6vectorI7StudentSaIS0_EE"
m = re.search(pattern, s)
if m:
print(m.group(2)[0: int(m.group(1))])
Output
Sort
Using _Z6__comp7StudentS_ will return __comp

How to get the content after a string using regex in python

I am having a string as follows:
A5697[2:10] = {ravi, rageev, raghav, smith};
I want the content after "A5697[2:10] =". So, my output should be:
{ravi, rageev, raghav, smith};
This is my code:
print(re.search(r'(?<=A\d+\[.*\] =\s).*', line).group())
But, this is giving error:
sre_constants.error: look-behind requires fixed-width pattern
Can anyone help to solve this issue? I would prefer to use regex.
You can try re.sub , like below, Since you have given only one data point. I am assuming all the other data points are following the similar pattern.
import re
text = "A5697[2:10] = {ravi, rageev, raghav, smith}"
re.sub(r'(A\d+\[\d+:\d+\]\s+=\s+)(.+)', r'\2', text)
returns,
'{ravi, rageev, raghav, smith}'
re.sub : substitutes the entire match as given as regex with the 2nd capturing group. The second capturing group captures every thing after '= '.
Simply replace the bits you don't want:
print re.sub(r'A\d[^=]*= *','',line)
See demo here: https://rextester.com/NSG17655

print(f"...:")-statement too long - break it into multiple lines without messing up the format

I have a console program with formatted output. to always get the same length of the printout, I have a rather complex formatted print output.
print(f"\n{WHITE_BG}{64*'-'}")
print(f"\nDirektvergleich{9*' '}{RED}{players[0].name}{4*' '}{GREEN}vs.{4*' '}{RED}{players[1].name}{CLEAR}\n")
print(f"""{15*'~'}{' '}{YELLOW}Gesamt{CLEAR}:{' '}{players[0].name}{' '}{GREEN}{int(player1_direct_wins)}{(int(4-len(player1_direct_wins)))*' '}-{(int(4-len(player1_direct_losses)))*' '}{int(player1_direct_losses)}{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-len(players[1].name))*'~'}\n""")
print(f"""{15*'~'}{' '}{YELLOW}Trend{CLEAR}:{' '}{players[0].name}{' '}{GREEN}{int(player1_trend_wins)}{(int(4-len(player1_trend_wins)))*' '}-{(int(4-len(player1_trend_losses)))*' '}{int(player1_trend_losses)}{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-len(players[1].name))*'~'}""")
print(f"\n{WHITE_BG}{64*'-'}")
This leads to the following output in my windows cmd
For readibility purpose, I tried to make the print over multiple lines, therefore I found on stackoverflow the idea to start with triple quotes. But when I cut this print(f"...") statement in the middle, I mess up my formatting.
Example:
print(f"\n{WHITE_BG}{64*'-'}") #als String einspeisen?!
print(f"\nDirektvergleich{9*' '}{RED}{players[0].name}{4*' '}{GREEN}vs.{4*' '}{RED}{players[1].name}{CLEAR}\n")
print(f"""{15*'~'}{' '}{YELLOW}Gesamt{CLEAR}:{' '}{players[0].name}{' '}{GREEN}{int(player1_direct_wins)}{(int(4-len(player1_direct_wins)))*' '}-
{(int(4-len(player1_direct_losses)))*' '}{int(player1_direct_losses)}{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-len(players[1].name))*'~'}\n""")
print(f"""{15*'~'}{' '}{YELLOW}Trend{CLEAR}:{' '}{players[0].name}{' '}{GREEN}{int(player1_trend_wins)}{(int(4-len(player1_trend_wins)))*' '}-
{(int(4-len(player1_trend_losses)))*' '}{int(player1_trend_losses)}{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-len(players[1].name))*'~'}""")
print(f"\n{WHITE_BG}{64*'-'}")
leads to...
can anyone point me in the right direction how to format my output in the displayed way, but without having this absurd long line length.
Thank you guys in advance!
Triple quoted strings preserve newline characters, so they are indeed not what you want here. Now when it finds two adjacent strings, the Python parser automagically concatenates them into a single string, i.e.:
s = "foo" "bar"
is equivalent to
s = "foobar"
And this works if you put your strings within parens:
s = ("foo" "bar")
in which case you can put each string on its own line as well:
s = (
"foo"
"bar"
)
This also applies to "fstrings" so what you want is something like:
print((
f"{15*'~'}{' '}{YELLOW}Gesamt{CLEAR}:{' '}{players[0].name}{' '}{GREEN} "
f"{int(player1_direct_wins)}{(int(4-len(player1_direct_wins)))*' '}-"
f"{(int(4-len(player1_direct_losses)))*' '}{int(player1_direct_losses)}"
f"{CLEAR}{' '}{players[1].name}{' '}{(28-len(players[0].name)-"
f"len(players[1].name))*'~'}\n"
))
That being said, I'd rather use intermediate variables than trying to cram such complex expressions in a fstring.

How to get the value after a string using perl reg expression

I have the following string :
{\"id\":01,\"start_time\":\"1477954800000\",\"stop_time\":\"1485817200000\",\"url\":http:://www.example.com\}
and I'd like to get for example the value of start_time (1477954800000).
I tried several things in https://regex101.com/ but I could not find a way to deal with the special characters (\":\") between the string and the value .
If the for example the string was like start_time = 1477954800000
I know that by using
start_time\":\"(\w+)/)
I'll get the value.
Any idea on how to get the value when \":\" are involved?
Your sample data looks like a stringified JSON object, if that is the case you should use a JSON parser not a regular expression:
#!perl
use strict;
use warnings;
use feature qw(say);
use JSON;
my $json_string = <DATA>;
chomp($json_string);
my $json_object = decode_json $json_string;
# get the value of the start_time key
say $json_object->{start_time};
# 1477954800000
__DATA__
{"id":1,"start_time":"1477954800000","stop_time":"1485817200000","url":"http://www.example.com"}

Python How to split a string when find the first numeric char

This is my string:
"Somestring8/9/0"
I need to get something like this:
['Somestring','8/9/0']
The moment I find a numeric char, I need to split the string to get:
'8/9/0'
This my code:
stringSample = "GigabitEthernet8/9/0"
print re.findall(r'(\w+?)(\d+)', stringSample)[0]
('GigabitEthernet', '8')
But I'm getting this result
What am I doing wrong?
I appreciate your help!!
Your second regex group accepts only digits. Allow it to include forward slashes too.
stringSample = "GigabitEthernet8/9/0"
print re.findall(r'(\w+?)([\d/]+)', stringSample)[0]
# ('GigabitEthernet', '8/9/0')
Try Using the re.split method to split your string in two, passing the maxsplit parameter
re.split('(\w+?)([\d/]+)', stringSample, 1)

Resources