How to compare strings in python - python

I am using python 2.7. I am running a linux command using python which prints out the wifi ssid available. I need to compare if the ssid I am trying to connect is available or not. I am using the below command to print the ssid:
import commands
ret = commands.getstatusoutput("sudo iwlist wlan0 scan | grep ESSID")
print(ret)
#output:
(0, ESSID="SSID1"\n
ESSID="SSID2"\n
ESSID="SSID3")
if I print print(ret[1]) then it gives below output:
ESSID="SSID1"
ESSID="SSID2"
ESSID="SSID3"
Lets say I am trying to connect to SSID2, how can I put this in a condition to check if SSID2 is available at this moment or not. Something like if ret[1] == "SSID2". I am new to python programming.
Thanks

ret[1] is a newline-separated string. Each line has an equals sign in it. You need an expression that evaluates to True when "SSID2" appears on the right-hand side of any equals sign.
data = '''\
ESSID="SSID1"
ESSID="SSID2"
ESSID="SSID3"'''
if any(x.split('=')[1][1:-1]=="SSID2" for x in data.splitlines()):
print("yes")
data.splitlines() returns a sequence of the lines in data (you could use ret[1] for this). For each line x, x.split('=') returns a list where the first element is the string to the left of the equals sign and the second is that to the right. So x.split('=')[1] is the right-hand side, and x.split('=')[1][1:-1] removes the first and last (quote) characters.
This is wrapped up in a generator expression that produces a sequence of arguments to the built-in any function, which returns True as soon as it encounters an argument that evaluates true.

if "SSID2" in "ret[1].split("\n")[1]":
print "yes"

Related

Why is my function returning blank strings, but works as expected in the python console?

Apologies for the poor title, I don't know how else to describe my situation.
I wrote a small pattern matching function.
def substrings(input_str):
'''Generate all leading substrings of an input string'''
for i in range(len(input_str)):
return input_str[:i]
It should return a series of slices of a string. If the input was ABCD, it should output ABCD, ABC, AB and A.
When I tested this function in the python console (shown below), it behaves correctly and outputs all the expected strings.
for i in range(len(input_str)):
print(input_str[:i])
But when used in the body of my program its returning nothing at all. For example;
test1 = substrings('ABCD')
print(test1)
Outputs blank lines and I'm struggling to figure out why.
In the console, your loop first prints out a blank string when i==0. Then it continues to loop and print out each of the characters in the string.
In the function, you are returning up to the 0th element in the array, which is the same blank string the console printed on the first time through the loop.
To see better what is happening in the console, you might print the index too:
for i in range(len(input_str)):
print('{0} {1}'.format(i, input_str[:i]))
That's because the first thing your functions returns is empty string ''. So you are exiting loop after first iteration for i = 0 and your variable is empty string because of the fact that:
>>> s = 'ABCD'
>>> s[:0]
''
You are returning in a loop. So the return is the last statement that would execute in a function. That is when a return statement is reached, the control leaves the function. So in the very first iteration i=0, the control returns '' and exits the function irrespective of for-loop. In console the output is obtained because I'm console each line is interpreted one-by-one unlike the program being compiled at once. So console shows the output. Hope this answer helps you
The issue is occurring because you are trying to return information in a loop. When the return statement is called, it exits the function. What you should do is use the yield keyword. Try doing this
def substrings(input_str):
for i in range(len(input_str)):
yield input_str[:i]
# Then iterate through the function like so
function = substrings()
for i in function:
print(i)
Your code should be working fine now!

Jupyter lab: why variable on single line does not generate output?

I follow a tutorial about Jupyter and Python, where it says that if two consecutive commands are the following:
in: x = 2
in: x
I should get
out: 2
as an result. However, the x on single line in a combined block like:
in: x = 2
in: if x == 2:
x
does not print the x variable. Is this x on single line somewhat different from x as a single command? When I write this I see, a line is different as whole command but what is the underlying concept or thing that makes the first two commands result 2 but the second three commands nothing?
This has to do with the difference between an expression and a statement (see below for links) in python.
An expression can only contain identifiers, literals and operators.
Statements can be significantly more complex. See simple statements and compound statements
The python shell will output the evaluation of an expression, but won't with a statement because there's no guarantee it evaluates to something that can be outputted. You should use print to output values from a statement.
Consider what would happen if you replaced x with its value (2):
if 2 == 2:
2
Would you expect the interpreter to output 2?
When you write a variable in a line and execute it jupyter notebook assumes that you want to know the value of the variable and implicitly converts it to print(variable) so the value of the variable is printed.
When you use multiple statement you will rarely want to print all variables used in the statements. So it is not implemented for this case

How do I fix this While statement in my Pythagorean theorem code?

So I am trying to write a simple code that will do the Pythagorean theorem for me after I input A, B and C but the code is skipping my While statements, and I have tried rewriting them as if statements to see if that works and again it will skip it, I need some help Please and Thank you Btw I do realize that in the picture that my while loops are open and have nothing ending them but I did have that in there at one point but I had taken them out when I changed to If statements.My Code I cant seem to understand
When you use input() the input comes as a string, and in your while loop you set your condition to be equal to 1 (as an integer).
A solution to this would be:
varname = int(input("")) #this way it converts your input into an integer
When you're taking input() from the user, it is returned as a string. Suppose user enters 1 it will be stored as "1" # which is a string. Now when you compared Yes_No == 1 it returned False because "1" == 1 is False.
So you need to parse (convert) it into a number (integer), which can be done by passing string to int() function. It will return the integer representation of that string. Do the same with all the inputs and your problem will be solved!
Another problem with your code is that you're not updating the value of Yes_No in any of the while loop. Which means that it will result in infinite loop, it will keep executing the while loop because once the condition becomes True it will not become False because value of Yes_No is not updated.
As the python documentation points out, the input function returns a string:
input([prompt])
If the prompt argument is present, it is written to standard output
without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
If you didn't know that and you wanted to debug and figure out, you can do something like print(type(Yes_No)) and you can see that it is a string type, so when you evaluate this expression: while Yes_No == 1, it returns false.
So the fix in this situation is to change your input line to
Yes_No = int(input("Do you have the hypotenuse? For yes press 1 or for no press 2"))

unable to convert python type str into a list array

i'm new to python, and i am developing a tool/script for ssh and sftp. i noticed some of the code i'm using creates what i thought was a string array
channel_data = str()
to hold the console output from an ssh session. if i check "type" on channel_data it comes back as class 'str' ,
but yet if i perform for loop to read each item in channel_data , and channel_data contains what appears to be 30 lines from an ssh console
for line in channel_data:
if "my text" in line:
found = True
each iteration of "line" shows a single character, as if the whole ssh console output of 30 lines of text is broken down into single character array. i do have \n within all the text.
for example channel_data would contain "Cisco Nexus Operation System (NX-OS) Software\r\nCopyright (c) 2002-2016\r\n ..... etc. etc.. ", but again would read in my for loop and print out "C" then "i" then "s" etc..
i'm trying to understand do i have a char array here or a string array here that is made up of single string characters and how to convert it into a string list based on \n within Python?
You can iterate a string just like a list in Python. So, yes, as expected, your string type channel_data will in fact give you every character.
Python does not have a char array. You will have a list of strings, even as a single character as each item in the list:
>>> type(['a', 'b'])
<type 'list'>
Also, just for the sake of adding some extra information for your own knowledge when it comes to usage of terminology, there is a difference between array and list in Python: Python List vs. Array - when to use?
So, what you are actually looking to do here is take the channel_data string and make it a list by calling the split method on it.
The split method will, by default, split on white space characters only. Check the documentation. So, you will want to make sure what you want to actually split on and provide that detail to the method.
You can take a look at splitlines to see if that works for you.
As specified in the documentation for splitlines:
Line breaks are not included in the resulting list unless keepends is
given and true.
Your result will then be a list of strings as you expect. So, as an example you can do:
your_new_list_of_str = channel_data.split('\n')
or
your_new_list_of_str = channel_data.splitlines()
string_list = channel_data.splitlines()
See docs at https://docs.python.org/3.6/library/stdtypes.html#str.splitlines

Regular expression further checking

I am working with a regular expression that would check a string,Is it a function or not.
My regular expression for checking that as follows:
regex=r' \w+[\ ]*\(.*?\)*'
It succefully checks whether the string contains a function or not.
But it grabs normal string which contains firs barcket value,such as "test (meaning of test)".
So I have to check further that if there is a space between function name and that brackets that will not be caught as match.So I did another checking as follows:
regex2=r'\s'
It work successfully and can differentiate between "test()" and "test ()".
But now I have to maintain another condition that,if there is no space after the brackets(eg. test()abcd),it will not catch it as a function.The regular expression should only treat as match when it will be like "test() abcd".
But I tried using different regular expression ,unfortunately those are not working.
Her one thing to mention the checking string is inserted in to a list at when it finds a match and in second step it only check the portion of the string.Example:
String : This is a python function test()abcd
At first it will check the string for function and when find matches with function test()
then send only "test()" for whether there is a gap between "test" and "()".
In this last step I have to find is there any gap between "test()" and "abcd".If there is gap it will not show match as function otherwise as a normal portion of string.
How should I write the regular expression for such case?
The regular expression will have to show in following cases:
1.test() abc
2.test(as) abc
3.test()
will not treat as a function if:
1.test (a)abc
2.test ()abc
(\w+\([^)]*\))(\s+|$)
Bascially you make sure it ends with either spaces or end of line.
BTW the kiki tool is very useful for debugging Python re: http://code.google.com/p/kiki-re/
regex=r'\w+\([\w,]+\)(?:\s+|$)'
I have solved the problem at first I just chexked for the string that have "()"using the regular expression:
regex = r' \w+[\ ]*\(.*?\)\w*'
Then for checking the both the space between function name and brackets,also the gap after the brackets,I used following function with regular expression:
def testFunction(self, func):
a=" "
func=str(func).strip()
if a in func:
return False
else:
a = re.findall(r'\w+[\ ]*', func)
j = len(a)
if j<=1:
return True
else:
return False
So it can now differentiate between "test() abc" and "test()abc".
Thanks

Categories