I probably have conjured up some sloppy code trying to get this resolved but what I really want to accomplish is take an IP Address from the command line and fit it into a string variable (theargis).
I am working with a code snippet to assure myself that I have the code worked out before integrating it into my main program, so I am printing the result to the screen.
It is working as such, but the problem is that I am seeing ['123.123.123.123'] instead of 123.123.123.123.
I have tried several ways to attempt to convert the list value in to a raw string without additional formatting, but I am losing the battle.
The question is how I get the final line of this to produce: The argument is: 123.123.123.123
Here is what I have right now...
import sys
theargis = ''
theargis +=str(sys.argv[1:])
print ("The argument is: " + theargis)
I'm fairly sure I am displaying just how green I am to Python but I want to resolve this! Thanks!
import sys
theargis = ''
theargis +=str(sys.argv[1])
print ("The argument is: " + theargis)
Related
I am writing a program in Python and want to replace the last character printed in the terminal with another character.
Pseudo code is:
print "Ofen",
print "\b", # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print "r"
I'm using Windows8 OS, Python 2.7, and the regular interpreter.
All of the options I saw so far didn't work for me. (such as: \010, '\033[#D' (# is 1), '\r').
These options were suggested in other Stack Overflow questions or other resources and don't seem to work for me.
EDIT: also using sys.stdout.write doesn't change the affect. It just doesn't erase the last printed character. Instead, when using sys.stdout.write, my output is:
Ofenr # with a square before 'r'
My questions:
Why don't these options work?
How do I achieve the desired output?
Is this related to Windows OS or Python 2.7?
When I find how to do it, is it possible to erase manually (using the wanted eraser), delete the '\n' that is printed in python's print statement?
When using print in python a line feed (aka '\n') is added. You should use sys.stdout.write() instead.
import sys
sys.stdout.write("Ofen")
sys.stdout.write("\b")
sys.stdout.write("r")
sys.stdout.flush()
Output: Ofer
You can also import the print function from Python 3. The optional end argument can be any string that will be added. In your case it is just an empty string.
from __future__ import print_function # Only needed in Python 2.X
print("Ofen",end="")
print("\b",end="") # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print("r")
Output
Ofer
I think string stripping would help you. Save the input and just print the string upto the length of string -1 .
Instance
x = "Ofen"
print (x[:-1] + "r")
would give you the result
Ofer
Hope this helps. :)
Working on a program for class. I have the following code, however, even though the code works fine; I have a formatting issue.
This here is the correct output that I am trying to get
This is what I currently have; and is wrong
Below is the current code I have:
num_rods = input ( "Input rods: You input " )
num_rods = float ( num_rods )
print ("rods.")
What is the error here? and how can I make my code look like the example; thanks.
Try
print('{} rods.'.format(num_rods))
or
print('rods: ',num_rods)
Also, be careful with statements of this type. Check what happens to the code if, instead of inputting an int or float, you pass the character 'a' for example.
You're seeing a line break, which cannot be avoided
Possible to get user input without inserting a new line?
But you can work around it
entered = input ( "Input rods: You input " ) # literally type "1.0 rods."
amount, _ = entered.split()
...
print ("Minutes to walk {:.1f} rods:".format(amount)) # but you're already printing this
I can't really find anything that really helps online so I thought I'd ask myself. I have the following code:
username = input()
username = username.capitalize()
print("Hello " + username ) # I want this to be centered
I want the print statement to be centered on whatever console it is being ran on. Thanks for the help!
There are two parts to this.
First, you need to get the console width. You do that with shutil.get_terminal_size.
Since it isn't always possible to get the console width—for that matter, there might not even be one (e.g., if your program's standard output is redirected to a file and doesn't even have a terminal), it will fall back to 80 columns (although you can override that if you want):
cols, rows = shutil.get_terminal_size()
Now you just center the string in that width. The fact that the string includes user input doesn't matter. Once you concatenate "Hello " and username, you've got a str that works the same as any other string object. So:
print(("Hello " + username).center(cols))
If it's possible that the user's input will be too long to fit on one line, you want to wrap it first, then center the lines. You can use the textwrap module for that:
for line in textwrap.wrap("Hello " + username, cols):
print(line.center(cols))
You can use os.get_terminal_size().columns to get the number of columns in the terminal and then print the necessary spaces to centralise your text:
import os
def print_centre(s):
print(' ' * ((os.get_terminal_size().columns - len(s))//2) + s)
Some improvements (as pointed out by abarnert):
shutil.get_terminal_size is more reliable than os.get_terminal_size.
You can use s.center(...) for more readability.
Which gives a neater solution:
import shutil
def print_centre(s):
print(s.center(shutil.get_terminal_size().columns))
I'm trying to parse a json file with python however some of the strings that are returned appear to be too long and are being cut off and creating problems when parsing. I'm trying to figure out a way to return the string with a limited number of characters in the string however I'm having some trouble figuring out the best way to do that.
Right now I'm trying to work with something like the below:
def clean_string(string_val):
return '\"' + string.replace(string_val,'\"','\'\'')+'\"'
return string.replace(string_val,'$','\$')
return string_val[:150]
However this isn't working and the script is still returning the full string.
Any thoughts on changes to the above code so that it could take a string of, say, 500 words and cut it down to 150 characters?
Thanks in advance! Please let me know if it would be helpful for me to include more information on this.
There's multiple returns in your function, so only the first one is firing and its returning on the first line. This should be close to what you want.
def clean_string(string_val):
string_val = '\"' + string_val.replace('\"','\'\'') + '\"'
string_val = string_val.replace('$','\$')
return string_val[:150]
I have a long list of numbers that I would like to input into my code through a raw_input. It includes numbers that are spaced out through SPACES and ENTER/RETURN. The list looks like this . When I try to use the function raw_input, and copy paste the long list of numbers, my variable only retains the first row of numbers. This is my code so far:
def main(*arg):
for i in arg:
print arg
if __name__ == "__main__": main(raw_input("The large array of numbers"))
How can I make my code continue to read the rest of the numbers?
Or if that's not possible, can I make my code acknowledge the ENTER in any way?
P.s. While this is a project euler problem I don't want code that answers the project euler question, or a suggestion to hard code the numbers in. Just suggestions for inputting the numbers into my code.
If I understood your question correctly, I think this code should work (assuming it's in python 2.7):
sentinel = '' # ends when this string is seen
rawinputtext = ''
for line in iter(raw_input, sentinel):
rawinputtext += line + '\n' #or delete \n if you want it all in a single line
print rawinputtext
(code taken from: Raw input across multiple lines in Python )
PS: or even better, you can do the same in just one line!
rawinputtext = '\n'.join(iter(raw_input, '') #replace '\n' for '' if you want the input in one single line
(code taken from: Input a multiline string in python )
I think what you are actually looking for is to directly read from stdin via sys.stdin. But you need to accept the fact that there should be a mechanism to stop accepting any data from stdin, which in this case is feasible by passing an EOF character. An EOF character is passed via the key combination [CNTRL]+d
>>> data=''.join(sys.stdin)
Hello
World
as
a
single stream
>>> print data
Hello
World
as
a
single stream