I am trying to position an input within a string in python.
For example, the console will read "I am ___ years old", and the input value completes the sentence. Is there a way to do this?
Not entirely sure what you want. If you just want the input to be placed into that string, you can, among others, use the new format strings (or just str.format, or the % operator):
age = input("What is your age? ")
print(f"I am {age} years old")
If your string actually has that ___ section and you want to insert the age there, you can first replace that with a proper format symbol and then use format:
import re
s = re.sub("_+", "{}", "I am ___ years old")
print(s.format(age))
If, as some suggested in comments, you might actually want the user to fill in the blank as they type, you can first print the line, then use \r and flush to go back to the beginning and then ask for the input, overwriting just as much so that the input cursor is on the ___ part.
print("I am ___ years old", end="\r", flush=True)
age = input("I am ")
print(age)
One more solution using console ANSI escape chars and module ansicon (needs once installing through python -m pip install ansicon), besides moving cursor it will also give nice things like coloring, etc. Escape chars thanks to this module will work both in Unix and Windows systems. Unix supports escape chars natively even without this module.
# Needs: python -m pip install
import ansicon
ansicon.load()
age = int(input('I am ___ years old' + '\x1b[D' * 13))
print('Your age is:', age)
Using escape chars many things can be done, e.g. coloring word years in green, using next line of code:
age = int(input('I am ___ \x1b[32myears\x1b[m old' + '\x1b[D' * 13))
which outputs:
Unix systems need no modules at all, thus code can be just two lines, this code you can see and try here online!
Color table for standard set of colors can be easily printed by next code, these numbers should be placed instead of 32 in code \x1b[32m above:
for first, last in [(30, 47), (90, 107)]:
for color in range(first, last + 1):
print(f'\x1b[{color}m{str(color).rjust(3)}\x1b[m ', end = '')
print()
which outputs:
This should solve your problem.
words_list= ["I","am","x","years","old"] # sentence having missing value as "x"
val = input("how many years old are you ?") # input the value of "x"
words_list[2] = val # replace the value of "x" at right place
print(' '.join(word for word in words_list)) # get the output with missing owrd at right place as sentence
user_input = ("how old are you ? : ")
print("you are ",user_input"," this old !")
Related
n=str(input("Enter your name"))
a=str(input("Where do you live?"))
print("Hello",n,"How is the weather at",a,"?")
How to Remove space between {a & ?} in the print statement?
An f-string will give you better control over the exact formatting:
print(f"Hello {n}. How is the weather at {a}?")
Commas in python add a space in the output.
No need to use str as inputs in python are already treated as strings.
You can use this:
n = input("Enter your name")
a = input("Where do you live?")
print("Hello",n,"How is the weather at",a+"?")
This concatenates the two strings.
OR
n = input("Enter your name")
a = input("Where do you live?")
print(f"Hello {n}! How is the weather at {a}?")
This is called f-strings. It formats the string so you can put the value of a variable in the output.
You can simply do it by using end inside the print
by default its value is \n and if you set it an empty string ''
it won't add anything(or any space).
after printing a and the ? will print exactly after that.
so you can write the code below:
print("Hello",n,"How is the weather at",a, end='')
print("?")
everyone. I am trying to solve a coding challenge as follows:
get a string from the user. Afterward, ask the user "What would you like to do to the string?", allow the user to choose the next functionalities:
"upper" - makes all the string upper case
"lower" - makes all the string lower case
" "spaces2newline" - reaplce all spaces in new lines
...
print the result
*Use a dictionary to "wrap" that menu
So, what I am getting from this is that I need to make a dictionary from which I can call commands and assign them to the string.
Obviously, this doesn't work:
commands = {"1" : .upper(), "2" : .lower(), "3" : .replace(" ",\n)}
user_string = input("Enter a string: ")
options = input("How would you like to alter your string? (Choose one of the following:)\n
\t1. Make all characters capital\n
\t2. Make all characters lowercase")
#other options as input 3, 4, etc...
But perhaps someone can recommend a way to make the idea work?
My main questions are:
Can you somehow assign built-in functions to a variable, list, or dictionary?
How would you call a function like these from a dictionary and add them as a command to the end of a string?
Thanks for any assisstance!
Use operator.methodcaller.
from operator import methodcaller
commands = {"1": methodcaller('upper'),
"2": methodcaller('lower'),
"3": methodcaller('replace', " ", "\n")}
user_string = input("Enter a string: ")
option = input("How would you like to alter your string? (Choose one of the following:)\
\t1. Make all characters capital\
\t2. Make all characters lowercase")
result = commands[option](user_string)
The documentation shows a pure Python implementation, but using methodcaller is slightly more efficient.
Well, chepner's answer is definitely much better, but one way you could have solved this is by directly accessing the String class's methods like so:
commands = {"1" : str.upper, "2" : str.lower, "3" : lambda string: str.replace(string, " ", "\n")} # use a lambda here to pass extra parameters
user_string = input("Enter a string: ")
option = input("How would you like to alter your string? (Choose one of the following:)\
\t1. Make all characters capital\
\t2. Make all characters lowercase")
new_string = commands[option](user_string)
By doing this, you're saving the actual methods themselves to the dictionary (by excluding the parenthesis), and thus can call them from elsewhere.
maybe you could do:
command = lambda a:{"1" : a.upper(), "2" : a.lower(), "3" : a.replace(" ",'\n')}
user_string = input("Enter a string: ")
options = input("How would you like to alter your string? (Choose one of the following:)")
print("output:",command(user_string)[options])
#\t1. Make all characters capital\n
I have the simple code:
answer= input("Have you started your first homework? ")
print("Your answer was:", answer,"!")
However every time I run this it prints the answer there is a space before the "!".
I cannot find a way to make the exclamation follow the answer directly. Why and how can I do that?
If you want to print the answer, you have a few options:
# Multiple args
print("Your answer was: ", answer, "!", sep="")
# String formatting
print("Your answer was: {}!".format(answer))
# String concatenation
print("Your answer was: " + answer + "!")
Python 3.6+:
# f-strings
print(f"Your answer was: {answer}!")
print has an argument called sep which, by default, is set to ' ' (a space). It will add that separator between every argument.
print function automatically adds a space between comma separated arguments.
So if you don't want that comma, don't pass them as separate arguments and use string formatting instead e.g.:
print("Your answer was:", "{}!".format(answer))
Here i've concatenated the strings using str.format:
"{}!".format(answer)
If you're in Python 3.6 or later, you can use f-strings:
f"{answer}!"
You can even use the printf style formatting:
"%s!" % answer
Try this:
print("Your answer was: "+answer"+"!")
I am new to python and trying to solve the following problem, answer is appreciate : (python 3)
Prompt the user to input an integer between 0 and 155, a float, a character, and a string, storing each into separate variables. Then, output those four values on a single line separated by a space.
I worked on it. Thank you for the feedback. New to stackoverflow
num = 99
num_float = 3.77
character = input("z")
string = input("Howdy")
print(str(num) + "\n" + str(num_float) + "\n" + character + "\n "+ string)
No one will probably give you a complete program like David said, but try using input() to prompt for each value, turning each value into a string with str(), adding them together with spaces in the middle, and printing the answer.
You don't need to input or output multiple values at once.
I was trying to make a program that could be used for one-time pad encryption by counting the number of characters and having a random number for each one. I started making a line that would let the program ignore spaces, but then I realized I would also need to ignore other symbols. I had looked at How to count the number of letters in a string without the spaces? for the spaces,
and it proved very helpful. However, the answers only show how to remove one symbol at a time. To do what I would like by using that answer, I would have to have a long line of - how_long.count('character')'s, and symbols that I may not even know of may still be copied in. Thus, I am asking for a way where it will only count all the alphabetic characters I write down in a list. Is this possible, and if so, how would it be done?
My code:
import random
import sys
num = 0
how_long = input("Message (The punctuation will not be counted)\n Message: ")
charNum = len(how_long) - how_long.count(' ')
print("\n")
print("Shift the letters individually by their respective numbers.")
for num in range(0, charNum-1):
sys.stdout.write(str(random.randint(1, 25))+", ")
print(random.randint(1, 25))
If your desired outcome is to clean a string so it only contains a desired subset of characters the following will work but, I'm not sure I totally understand what your question is so you will probably have to modify somewhat.
desired_letters = 'ABCDOSTRY'
test_input = 'an apple a day keeps the doctor away'
cleaned = ''.join(l for l in test_input if l.upper() in desired_letters)
# cleaned == 'aaadaystdoctoraay'
Use Regex to find the number of letters in the input:
import re, sys, random
how_long = input("Message (The punctuation will not be counted)\n Message: ")
regex_for_letters = "[A-Za-z]"
letter_count = 0
for char in how_long:
check_letter = re.match(regex_for_letters, char)
if check_letter:
letter_count += 1
print(letter_count)
for num in range(0, letter_count-1):
sys.stdout.write(str(random.randint(1, 25))+", ")
print(random.randint(1, 25))
Filter the string:
source_string='My String'
allow_chars=['a','e','i','o','u'] #whatever characters you want to accept
source_string_list=list(source_string)
source_string_filtered=list(filter(lambda x: x in allow_chars,source_string_list))
the count would be: len(source_string_filtered)