Remove space in print command for some specific values - python

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("?")

Related

How do I make an input() detect if the user input is something other than a string?

I am fairly new to Python and I wanted to generate a simple user input that asks for your name. I got the prompt to work but when I added code that detects if the input is not a string, it doesn't let me input anything at all.
It was working up until I added the code that tells the user if they used an unsupported character.
Here's the code I have so far:
while True:
name = input('What is your name? ')
if name is str:
print('Hi,%s. ' % name)
if name != str:
print('That is not a valid character!')
Python supplies methods to check if a string contains on alphabets, alphanumeric or numeric.
isalpha() returns True for strings with only alphabets.
isalnum() returns True for strings with only alphabets and numbers and nothing else.
isdigit() returns True for strings with only numbers.
Also your if-else statement is off
name = input('What is your name? ')
if name.isalpha():
print('Hi,%s. ' % name)
else:
print('That is not a valid character!')
When you do
name = input('What is your name? ')
you get a string called name, so checking it it is a string won't work.
What you can check is if it's an alphabetical character, using isalpha:
if name.isalpha():
# as you were
There are various other string methods ( see here ) which start is to check for numbers, lower case, spaces and so on.

question related to formatting . Usage of format() in python

could anyone explain how format() works in python? where to use it, and how to use it?. I am not getting even I about this keyword
You can regarding it as a kind of string replacement.
{} part in the string -> string.format() content
Definition: https://www.w3schools.com/python/ref_string_format.asp
A pratical example can be like this:
base_url = 'www.xxxx.com/test?page={}'
for i in range(10):
url = base_url.format(i)
do sth
The format() method formats the specified value(s) and insert them inside the string's placeholder.
txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
Here fname will be replaced by John and age will be replaced by 36, if you print txt1.
Alternatively you can use f strings .
eg:
fname= "John"
age= 36
print(f"My name is {fname}, I'm {age}")
Even it will print the same output.
Format is often applied as a str-type method: txt.format(...), where type(txt)='str'.
This function is used to insert values inside string's placeholders. Placeholders are curly brackets {} placed inside a string and the format() method returns a formatted string with the values plugged into the string.
This function also enables formatting different type of variables in different ways. E.g. float with value 0.0001 can be represented in floating point representation: 0.0001 or scientific representation 1e-4 using different specifires.
Usage:
txt = "My name is {name}. I'm {age} years old."
print(txt.format(name="Dan", age=32))
Will output: 'My name is Dan. I'm 32 years old.'
You can use positional arguments as well:
txt = "My name is {}. I'm {} years old."
print(txt.format("Dan", 32))
Where the values are taken by their order.
This will output the same result.
To format with different formatting you can use specifiers:
txt = "Decimal numbers: {number:d}"
print(txt.format(number=8340))
txt = "Fix point numbers: {number:.2f}"
print(txt.format(number=3.1415))
There are other specifiers that have other formatting behavior like centering some value to match some desired width:
txt = "{center:^20}"
print(txt.format(center='center'))
This will output ' center ' which contains exactly 20 characters.
There are many more formatting options that you can browse here
or in many other rescorces.

Assigning and Calling built-in functions from a dictionary (Python)

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

Part 2, Remove All From String problem in python

I can't figure out what I need to add to make my code work, this is what I have:
my_string = input("Enter a word: ")
part_to_remove = input("Enter a part of the word to remove: ")
def remove_all_from_string(my_string):
while my_string != "bas":
index = my_string.find(part_to_remove)
return index
print remove_all_from_string(my_string)
I can't figure out what to add next, the test cases tells me to
Use the find function
Use a while loop
Use string concatenation
Use string indexing
Use the len function
Test the code with "bananas"
Test the code by replacing "na"
With the specified test info your code should return "bas"
I don't know what I could possibly do to match these and still make the code work
You can simply use the replace function of strings:
my_string = input("Enter a word: ")
paet_to_remove = input("Enter a part of the word to remove: ")
my_string = my_string.replace(paet_to_remove, "")
I am not going to write that code for you, but I will try to clarify some of the pointers:
use find and string indexing (actually string slicing) to get the part of the string before the part to remove
use find, len, and string slicing to get the part after the part to remove
use string concatenation to combine them and replace the original string
use while and find to continue while the part to remove exists in the string
test the function with parameters "bananas" and "na", and compare the result to "bas", but do not "hard-code" any of that into your function
With those steps, you should be able to write the function on your own.
Similar to the answer of #kevin
my_string = input("Enter a word: ")
paet_to_remove = input("Enter a part of the word to remove: ")
print( ''.join(my_string.split(paet_to_remove)) )

Editing user-input string values in Python

I was wondering how to edit a string value input by user such that the first character of the string (and every occurrence of that same character) are replaced by another character (ie !)
IE if the user enters Pineapples they get !ineapples
but if they enter pineapples they get !inea!!les
Any help is very much appreciated
Here is what I Have so far
string1 = input("Enter a string: ")
svalue1 = string1[0]
string2 = string1.replace('string1[0]' , '!')
I'm guessing one of my issues is that I'm not using the replace function properly
You can try this function:
def RepFirstWith(s,c):
return s.replace(s[0],c)
For example:
print RepFirstWith('pineapples','!') # !iena!!les
Something like this:
>>> s = raw_input("Please enter a string: ")
Please enter a string: pineapples
>>> print s.replace(s[0], '!')
!inea!!les
All done and tested in Python shell
The problem was is that you wrote string1[0] which literally makes a string that is 'string1[0]' instead of computing that value

Categories

Resources