Output is not getting string + integer - python

#!/usr/bin/env python
import os,subprocess,re
f=open("/var/tmp/disks_out","w")
proc=subprocess.Popen(['df', '-h'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=False)
out,err=proc.communicate()
for line in out:
f.write(line)
f.close()
f1=open("/var/tmp/disks_out","r")
disks=[]
for line in f1:
m=re.search(r'(c.*s0)',line)
if m:
disk=m.group(1)
disks.append(disk)
disks = disks[0][:-1]
slices =[disks+i for i in str(range(5))]
print(slices)
and the out put i am getting below:
['c0t5000CCA025A29894d0s0', 'c0t5000CCA025A29894d0s1', 'c0t5000CCA025A29894d0s3', 'c0t5000CCA025A29894d0s4', 'c0t50 00CCA025A29894d0s5', 'c0t5000CCA025A29894d0s6']
But i want to get output similar too:
c0t5000CCA025A29894d0s1,c0t5000CCA025A29894d0s2,c0t5000CCA025A29894d0s3

If you want to get it with commas:
print(','.join(slices))
or rather for python 2.7:
print ','.join(slices)
What you printed out was list, so python interpreted it as one. join() method joins every element of the iterable by passed string, more info here (for Python 2.7 as you put in tag) but it seems you are using Python 3 here.

Related

Print specified output in subrocess

I want to print specified output in subrocess
Here is my code:
from subprocess import check_output
output = check_output(['python3', 'code.py']).decode('ascii')
print(output)
The output is:
Tom
John
How can I print just Tom or just John instead of both of them?
I have tried print(output[0]) to print Tom but I get only T.
You have single string and you can use any string's function.
You can split it and create list with lines
lines = output.split('\n')
And then display only first line
print(lines[0])
Let's take a look on steps you've already done:
You call check_output() and it returns output in the form of bytes;
Then You call bytes.decode(), which returns str.
As a result you get multi-line string. You've tried to access to first line using index 0, but you got first char instead of first line. It happened, cause accessing to string by index will return you char from this index.
To get first line you should split lines of your multi-line string (convert str to list of str). There's built-in function str.splitlines() which does what you need.
So, to upgrade your code we need to add one more line before your print() statement:
output_lines = output.splitlines()
After that you can access to line by index:
print(output_lines[0])

Python: split line by comma, then by space

I'm using Python 3 and I need to parse a line like this
-1 0 1 0 , -1 0 0 1
I want to split this into two lists using Fraction so that I can also parse entries like
1/2 17/12 , 1 0 1 1
My program uses a structure like this
from sys import stdin
...
functions'n'stuff
...
for line in stdin:
and I'm trying to do
for line in stdin:
X = [str(elem) for elem in line.split(" , ")]
num = [Fraction(elem) for elem in X[0].split()]
den = [Fraction(elem) for elem in X[1].split()]
but all I get is a list index out of range error: den = [Fraction(elem) for elem in X[1].split()]
IndexError: list index out of range
I don't get it. I get a string from line. I split that string into two strings at " , " and should get one list X containing two strings. These I split at the whitespace into two separate lists while converting each element into Fraction. What am I missing?
I also tried adding X[-1] = X[-1].strip() to get rid of \n that I get from ending the line.
The problem is that your file has a line without a " , " in it, so the split doesn't return 2 elements.
I'd use split(',') instead, and then use strip to remove the leading and trailing blanks. Note that str(...) is redundant, split already returns strings.
X = [elem.strip() for elem in line.split(",")]
You might also have a blank line at the end of the file, which would still only produce one result for split, so you should have a way to handle that case.
With valid input, your code actually works.
You probably get an invalid line, with too much space or even an empty line or so. So first thing inside the loop, print line. Then you know what's going on, you can see right above the error message what the problematic line was.
Or maybe you're not using stdin right. Write the input lines in a file, make sure you only have valid lines (especially no empty lines). Then feed it into your script:
python myscript.py < test.txt
How about this one:
pairs = [line.split(",") for line in stdin]
num = [fraction(elem[0]) for elem in pairs if len(elem) == 2]
den = [fraction(elem[1]) for elem in pairs if len(elem) == 2]

removing space from string in python

def digits_plus(test):
test=0
while (test<=3):
print str(test)+"+",
test = test+1
return()
digits_plus(3)
The output is:
0+ 1+ 2+ 3+
However i would like to get: 0+1+2+3+
Another method to do that would be to create a list of the numbers and then join them.
mylist = []
for num in range (1, 4):
mylist.append(str(num))
we get the list [1, 2, 3]
print '+'.join(mylist) + '+'
If you're stuck using Python 2.7, start your module with
from __future__ import print_function
Then instead of
print str(test)+"+",
use
print(str(test)+"+", end='')
You'll probably want to add a print() at the end (out of the loop!-) to get a new-line after you're done printing the rest.
You could also use the sys.stdout object to write output (to stdout) that you have more fine control over. This should let you output exactly and only the characters you tell it to (whereas print will do some automatic line endings and casting for you)
#!/usr/bin/env python
import sys
test = '0'
sys.stdout.write(str(test)+"+")
# Or my preferred string formatting method:
# (The '%s' implies a cast to string)
sys.stdout.write("%s+" % test)
# You probably don't need to explicitly do this,
# If you get unexpected (missing) output, you can
# explicitly send the output like
sys.stdout.flush()

Calling variable inside insert()

I have two text files which I'm trying to work with in python 2.7.7, structured as in these examples:
sequence_file.txt:
MKRPGGAGGGGGSPSLVTMANSSDDGYGGVGMEAEGDVEEEMMACGGGGE
positions.txt
10
7
4
What I want to do is insert a # symbol into the sequence at every position indicated in positions.txt:
MKR#PGG#AGGG#GGSPSLVTMANSSDDGYGGVGMEAEGDVEEEMMACGGGGE
At the moment, my code is as follows:
# Open sequence file, remove newlines:
with open ("sequence_file.txt", "r") as seqfile:
seqstring=seqfile.read().replace('\n', '').replace('\r', '')
# Turn sequence into list
seqlist = list(sequence)
# Open positions.txt, and use each line as a parameter for the insert() function.
with open("positions.txt") as positions:
for line in positions:
insertpoint = line.rstrip('\n')
seqlist.insert(insertpoint, '#')
seqlist = list(sequence)
The last block of that code is where it falls down. I'm trying to have it read the first line, trim the newline character (\n) and then use that line as a variable (insertpoint) in the insert() command. However, whenever I try this it tells me:
Traceback (most recent call last):
File "<pyshell#8>", line 4, in <module>
seqlist.insert(insertpoint, '#')
TypeError: an integer is required
If I test it out and try 'print insertpoint' it produces the number correctly, and so my interpretation of the error is that when I use the insert() command it is reading 'insertpoint' as text rather than the variable that was just set.
Can anyone suggest what might be going wrong with this?
What happens is that str.rstrip() returns a string, but insert() expects an integer.
Solution: Convert that string into an integer:
insertpoint = int(line.rstrip('\n'))
Note: When you print insertpoint it is shown without the '' but it is a string. You can check this by printing its type:
print(type(insertpoint)) # <type 'str'>
It appears you might need to put int() around insertpoint:
seqlist.insert(int(insertpoint), '#')

Put function outputs to a list in Python [duplicate]

This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
How to concatenate (join) items in a list to a single string
(11 answers)
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed 8 months ago.
The aim of the following program is to convert words in 4 characters from "This" to "T***", I have done the hard part getting that list and len working.
The problem is the program outputs the answer line by line, I wonder if there is anyway that I can store output back to a list and print it out as a whole sentence?
Thanks.
#Define function to translate imported list information
def translate(i):
if len(i) == 4: #Execute if the length of the text is 4
translate = i[0] + "***" #Return ***
return (translate)
else:
return (i) #Return original value
#User input sentense for translation
orgSent = input("Pleae enter a sentence:")
orgSent = orgSent.split (" ")
#Print lines
for i in orgSent:
print(translate(i))
On py 2.x you can add a , after print:
for i in orgSent:
print translate(i),
If you're on py 3.x, then try:
for i in orgSent:
print(translate(i),end=" ")
default value of end is a newline(\n), that's why each word gets printed on a new line.
Use a list comprehension and the join method:
translated = [translate(i) for i in orgSent]
print(' '.join(translated))
List comprehensions basically store the return values of functions in a list, exactly what you want. You could do something like this, for instance:
print([i**2 for i in range(5)])
# [0, 1, 4, 9, 16]
The map function could also be useful - it 'maps' a function to each element of an iterable. In Python 2, it returns a list. However in Python 3 (which I assume you're using) it returns a map object, which is also an iterable that you can pass into the join function.
translated = map(translate, orgSent)
The join method joins each element of the iterable inside the parentheses with the string before the .. For example:
lis = ['Hello', 'World!']
print(' '.join(lis))
# Hello World!
It's not limited to spaces, you could do something crazy like this:
print('foo'.join(lis))
# HellofooWorld!
sgeorge-mn:tmp sgeorge$ python s
Pleae enter a sentence:"my name is suku john george"
my n*** is s*** j*** george
You just need to print with ,. See last line of below pasted code part.
#Print lines
for i in orgSent:
print (translate(i)),
For your more understanding:
sgeorge-mn:~ sgeorge$ cat tmp.py
import sys
print "print without ending comma"
print "print without ending comma | ",
sys.stdout.write("print using sys.stdout.write ")
sgeorge-mn:~ sgeorge$ python tmp.py
print without ending comma
print without ending comma | print using sys.stdout.write sgeorge-mn:~ sgeorge$

Categories