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))
Related
I want to separate the users input using two different separators which are ":" and ";"
Like the user should input 4 subject and it's amounts. The format should be:
(Subject:amount;Subject:amount;Subject:amount;Subject:amount)
If the input is wrong it should print "Invalid Input "
Here's my code but I can only used one separator and how can I control the users input?
B = input("Enter 4 subjects and amount separated by (;) like Math:90;Science:80:").split(";")
Please help. I can't figure it out.
If you are fine with using regular expressions in python you could use the following code:
import re
output_list = re.split("[;:]", input_string)
Where inside the square brackets you include all the characters (also known as delimiters) that you want to split by, just make sure to keep the quotes around the square brackets as that makes a regex string (what we are using to tell the computer what to split)
Further reading on regex can be found here if you feel like it: https://medium.com/factory-mind/regex-tutorial-a-simple-cheatsheet-by-examples-649dc1c3f285
However, if you want to do it without importing anything you could do this, which is another possible solution (and I would recommend against, but it gets the job done well):
input_string = input_string.replace(";", ":")
output_list = input_string.split(":")
Which works by first replacing all of the semicolons in the input string with colons (it could also work the other way around) and then splitting by the remaining character (in this case the colons)
Hope this helped, as it is my first answer on Stack overflow.
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)
I need to create a box with parameters that prints any input the user puts in. I figured that the box should be the length of the string, but I'm stuck with empty code, because I don't know where to start.
It should look like this:
I agree with Daniel Goldfarb comments. Don't look for help without trying.
If you still couldn't get how to do that, then only read my remaining comment.
Just print :
str = string entered
len(str) = string length
+-(len(str) * '-')-+
| str |
+-(len(str) * '-')-+
So hopefully you can learn, don't want to just write the code for you. Basically break it into steps. First you need to accept user input. If you don't know how to do that, try googling, "python accept user input from stdin" or here is one of the results from that search: https://www.pythonforbeginners.com/basics/getting-user-input-from-the-keyboard
Then, as you mentioned, you need the length of the string that was input. You can get that with the len function. Then do the math: It looks like you want "|" and two spaces on each side of the string, giving the length plus 6 ("| " on either side). This new length is what you should make the "+---+" strings. Use the print() function to print out each line. I really don't want to say much more than that because you should exercise your brain to figure it out. If you have a question on how to generate "+---+" of the appropriate length (appropriate number of "-" characters) you can use string concatenation and a loop, or just use the python string constructor (hint: google "construct python string of len repeat characters"). HTH.
One more thing, after looking at your code, in addition to my comment about printing the string itself within the box, I see some minor logic errors in your code (for example, why are you subtracting 2 from the width). THE POINT i want to me here is, if you ware going to break this into multiple small functions (a bit overkill here, but definitely a good idea if you are just learning as it teaches you an important skill) then YOU SHOULD TEST EACH FUNCTION individually to make sure it does what you think and expect it to do. I think you will see your logic errors that way.
Here is the solution, but I recommend to try it out by yourself, breakdown the problem into smaller pieces and start from there.
def format(word):
#It declares all the necessary variables
borders =[]
result = []
# First part of the result--> it gives the two spaces and the "wall"
result.append("| ")
# Second part of the result (the word)
for letter in word:
result.append(letter)
# Third part of the result--> Ends the format
result.append(" |")
#Transforms the list to a string
result = "".join(result)
borders.append("+")
borders.append("--"+"-"*len(word)+"--")
borders.append("+")
borders="".join(borders)
print(borders)
print(result)
print(borders)
sentence = input("Enter a word: ")
format(sentence)
I'm new to Python, and I've found this solution. Maybe is not the best solution, but it works!
test = input()
print("+-", end='')
for i in test:
print("-", end='')
print("-+")
print("| " + test + " |")
print("+-", end='')
for i in test:
print("-", end='')
print("-+")
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]
As the title suggests, I want to get a string, split it into individual bits to input into something like ord('') and get a value for each individual character in that string. Still learning python so things like this get super confusing :P. Furthermore, the process for encryption for each of the codes will just be to shift the alphabet's dec number by a specified value and decrypt into the shifted value, plus state that value for each character. How would i go about doing this? any and all help would be greatly appreciated!
message=input("Enter message here: ", )
shift=int(input("Enter Shift....explained shift: ", )
for c in list(message):
a=ord(c)
print c
This is the very basic idea of what i was doing (was more code but similar), but obviously it didn't work :C, the indented--> just means that it was indented, just don't know how to do that in stack overflow.
UPDATE: IT WORKS (kinda) using the loop and tweaking it according to the comments i got a list of every single ascii dec value for each character in the string!, ill try and use #Hugh Bothwell's suggestion within the loop and hopefully get some work done.
mystring = "this is a test"
shift = 3
encoded = ''.join(chr(ord(ch) + shift) for ch in mystring)
You'll have to do a little more if you want your alphabet to wrap around, ie encode('y') == 'b', but this should give you the gist of it.