How to add input in the middle of a string? - python

I'm very new to programming, only started learning python ~4 days ago and I'm having trouble figuring out how to print a user input as a string, in between other strings on the same line. Being so new to programming, I feel like the answer is staring me right in the face but I don't have the tools or the knowledge to figure it out lol.
what I'm trying to do is:
Wow (PlayerName) that's cool
so far what I have is:
name = input("Name? ")
print("Wow") (print(name)) (print("that's cool"))
python came back with an error saying object 'NoneType' is not callable, so instead i tried to write it as a function and call that instead:
name = input("Name? ")
def name_call():
print(name)
print("Wow") (name_call()) (print("that's cool"))
same issue, I tried various similar things, but at this point I'm just throwing darts
I'm not 100% sure why neither of these worked, but I do know that it probably has something to do with me writing it incorrectly. I could just print the name on a new line, but I want to try and put them all on the same line if possible.

you can try this code:
# Python3 code to demonstrate working of
# Add Phrase in middle of String
# Using split() + slicing + join()
# initializing string
test_str = 'Wow that\'s cool!'
# printing original string
print("The original string is : " + str(test_str))
# initializing mid string
mid_str = (input('Please input name = '))
# splitting string to list
temp = test_str.split()
mid_pos = len(temp) // 3
# joining and construction using single line
res = ' '.join(temp[:mid_pos] + [mid_str] + temp[mid_pos:])
# printing result
print("Formulated String : " + str(res))
The result will be like this:
The original string is : Wow that's cool!
Please input name = Alice
Formulated String : Wow Alice that's cool!
you can input any name to the program.

As others have said, I think you're looking for string interpolation. As of Python 3.6 we have f-strings.
name = input("Name? ")
print(f"Wow {name} that's cool")
https://www.programiz.com/python-programming/string-interpolation

Your print's need to be on new lines.
name = input("Name? ")
print("Wow")
print(name)
print("that's cool")
Python thinks you are trying to call the result of the print function (which returns None) as a function of its own.
|
V you are accidentally calling the return value here
print("Wow")(print(name))

val = 'name'
print(f"Wow {val} that's cool.")
Btw, if you want name_call() to play a role, the following code also works
def name_call():
return ('name')
print(f"Wow {name_call()} that's cool.")

You may use the format method to insert name into the string's placeholder {}:
print("Wow {} that's cool".format(str(name)))

x = str(input('Name: '))
print('user entered {} as their name'.format(x))

Related

Weird error in loop not understanding why the range is out of index

I was asked to:-
Write a program to input a string and then using a function change(), create a new string
with all the consonants deleted from the string. The function should take in the string as
a parameter and return the converted string.
my code :-
str=input("enter a string: ")
def change(stri):
for i in range(0,len(stri)):
for e in ['a','e','i','o','u','A','E','I','O','U']:
if stri[i]==e:
if i==len(stri)-1:
stri = stri[0:i-1] + "" + stri[i: ]
else:
stri = stri[0:i] + "" + stri[i+1: ]
else:
continue
return stri
str=change(str)
print(str)
output :-
Traceback (most recent call last):
File "main.py", line 13, in <module> str=change(str)
File "main.py", line 5, in change if stri[i]==e:
IndexEnoi: string index out of range
^ for any string
Please someone help me out this is my imp project
As said by Johny Mopp: "Let's say len(stri) == 10. Your for loop then is for i in range(0, 10):. But then in the loop you modify stri so that it's new length is less than 10. You will now get an index out of range error at if stri[i]==e: because i is too large"
Use this instead:
text=input("enter a string: ")
vowels = ['a','e','i','o','u','A','E','I','O','U']
for x in vowels:
text = text.replace(x,"")
print(text)
Generally speaking, don't try to reinvent the wheel. Make use of all functions Python offers you.
The issue you are facing is common when deleting from the same object that you are iterating. Eventually you delete a part of the object that is already queued up as part of a future iteration in the for loop and you get an error.
The best way around this, in your case, is to write your vowel only string out to a new variable keeping your stri variable intact as it was passed into your function.
A quick rewrite of your code with the addition of the new variable to catch your output string would look like:
vowels=['a','e','i','o','u','A','E','I','O','U']
stri='This is a test string'
stro=''
for character in stri:
if character in vowels:
stro=stro+character
print(stro)
I believe the issue you have is that you change the string inside the for loop. You delete letters but still have the same range (len(stri) is not updated while changing the stri). Try with the word without vowels. You will not get any error.
But there is a much simpler way of doing this if I understand your task correctly.
def change2(str):
return ''.join([letter for letter in str if letter not in ['a','e','i','o','u','A','E','I','O','U']])
print(change2(input('enter a string: ')))
The join method creates the new string and returns it. The separator between the list elements is a string that calls join() method. In this example, it is an empty string.
You should use a new string variable for concatenation. You are changing the passed string to the function that's why it gives the error.
str=input("enter a string: ")
def change(stri):
nstr = ''
for i in range(0,len(stri)):
for e in ['a','e','i','o','u','A','E','I','O','U']:
print(stri[i])
if stri[i]==e:
if i==len(stri)-1:
nstr = stri[0:i-1] + "" + stri[i: ]
else:
nstr = stri[0:i] + "" + stri[i+1: ]
else:
continue
return nstr
str=change(str)
print(str)

How to remove commas from printed result?

I need to print this list without the commas, but I can't seem to figure out how.
data = (
('Sabrina Bryan,1/3/98,ss9387,f9;s1;m1,99km'),
('Fergus Connon Archer,11/21/89,ss5246,f1;s3,102km'),
('Adrian Harvey,3/3/78,ss1654,m5;s2,72km'),
('Patricia Abigail Wolf,9/5/00,ss0936,f3;s4;m8,134km'),
('Georgina Kramer,6/15/95,ss4837,f5;s2;m1,55km'),
('Glenn Julian Ayala,3/19/90,ss3689,s4;f3,152km'),
('Anita Davila,6/27/91,ss9367,f8,203km'),
('Gertrude Nunez,1/12/97,ss3948,s3;m1,34km'),
('Solomon Burton,8/5/88,ss7364,s2;f1,23km'),
('Rafael John Murray,10/19/01,ss9105,s9;f3,78km')
)
info = input("What would you like to do? ")
if info == 'b':
for line in data:
fname0 = data[0].split(' ')
lname0 = fname0[1].split(',')
bday0 = lname0[1].split('/')
def Sabrina(fname0, bday0):
print(fname0[0], *bday0[0:2], sep = ', ')
print(Sabrina(fname0, bday0))
It is printing "Sabrina, 1, 3" when I want it to print "Sabrina 1 3". I have tried using the .replace command, *bday0[0:2].replace(',', ' '), but it just gives me an error. Any tips?
You don't need .replace().
print(fname0[0], *bday0[0:2])
or
print(fname0[0], *bday0[0:2], sep = ' ')
will give you the desired output.
I figured out a quick solution for your problem:
It is based on the use of F-Strings. With this formatting-solution, you can quickly format your strings by implementing your variables without losing sight of the format of your output, also adding a return to the function.
Function Code Snippet
def Sabrina(fname0, bday0):
return f"{fname0[0]}, {bday0[0]} {bday0[1]}"
Here is more information related to the f-strings formatting explained.
It would be a great improvement if you could work around the issue that the values are hardcoded. But for a quick implementation this should help.
Let me know if this answers your question.
Cheers!
Full Working Code-Snippet
data = (
('Sabrina Bryan,1/3/98,ss9387,f9;s1;m1,99km'),
('Fergus Connon Archer,11/21/89,ss5246,f1;s3,102km'),
('Adrian Harvey,3/3/78,ss1654,m5;s2,72km'),
('Patricia Abigail Wolf,9/5/00,ss0936,f3;s4;m8,134km'),
('Georgina Kramer,6/15/95,ss4837,f5;s2;m1,55km'),
('Glenn Julian Ayala,3/19/90,ss3689,s4;f3,152km'),
('Anita Davila,6/27/91,ss9367,f8,203km'),
('Gertrude Nunez,1/12/97,ss3948,s3;m1,34km'),
('Solomon Burton,8/5/88,ss7364,s2;f1,23km'),
('Rafael John Murray,10/19/01,ss9105,s9;f3,78km'))
info = input("What would you like to do? ")
if info == 'b':
for line in data:
fname0 = data[0].split(' ')
lname0 = fname0[1].split(',')
bday0 = lname0[1].split('/')
def Sabrina(fname0, bday0):
return f"{fname0[0]} {bday0[0]} {bday0[1]}"
print(Sabrina(fname0, bday0))

python len method not good

So I am trying to do the MacDonald challenge.Given a function with the parameter "name", return the MacDonald version of it, the 1st and 4th letter being capitalized.
If I try the code without any if else and I pass in just "mac" an error occurs.So I said that if the length of name is less than 5 letters, print out that name is too short.Otherwise, do the macdonald version.
However, for some reason len() gives out an error here.
def old_macdonald(name):
firstLetter = name[0].capitalize()
fourthLetter = name[3].capitalize()
inBetween = name[1:3]
last = name[4:]
newName = firstLetter + inBetween + fourthLetter + last
if len(newName) < 4:
print("name is too short.")
else:
print(newName)
old_macdonald("mac")
I don't think len is throwing the exception, but just as the version without if condition the string manipulation does.
Do the string manipulation in the else part of your code to avoid the exception.
Following Jens' advice, I included the if check above everything else (since you want to terminate the function if the name is too short) and returned in the if-check to break end the function.
def old_macdonald(name):
if len(name)< 4:
print("name is too short.")
return
firstLetter = name[0].capitalize()
fourthLetter = name[3].capitalize()
inBetween = name[1:3]
last = name[4:]
newName = firstLetter + inBetween + fourthLetter + last
print(newName)
old_macdonald("mac")
old_macdonald("macdonald")
Here is the result
You are still trying to perform the same operations anyway, len is not throwing you an error, the above part of the code is giving you error.
Simply move your code to the else part of function and you should be fine. The reason you need to do this is because you need to check first, and then perform, instead of performing and then checking.

How to concatenate two functions on the same line?

def headName():
print (Name[0].upper())
def tailName():
print (Name[1:].lower())
Name = input("Please enter a name ")
headName()
tailName()
That's my code; I want to know how to concatinate headName() and tailName(), so that they're on the same line. Thanks
You can't do that without rewriting the functions. The newline is added by print. Since you call print inside the functions, nothing you do outside the function can undo the newline that was already added inside.
A better idea is to have your functions return the values, and then do the printing outside:
def headName():
return Name[0].upper()
def tailName():
return Name[1:].lower()
Name = input("Please enter a name ")
print(headName(), tailName(), sep="")
Incidentally, what you are doing can also be accomplished directly with Name.title().
To print on the same line call them in one print statement, something like:
print(headName(), ' ', tailName())
You can also use string formatting, which in case that you wanted to customize further the output would give you more control over the outcome:
def headName():
return Name[0].upper()
def tailName():
return Name[1:].lower()
Name = input("Please enter a name ")
print('{}{}'.format(headName(), tailName()))
You can also try:
def headName():
print ((Name[0].upper()), end="")
This will cause your print function to end with nothing, instead of ending with a newline (default).
For more information: https://docs.python.org/3/whatsnew/3.0.html

Brain going to explode. Need to search external file and return muliple results

I'm not going to lie. I'm trying to do an assignment and I'm being beaten by it.
I need to have python prompt the user to enter a room number, then lookup that room number in a supplied .txt file which has csv [comma-separated values], and then show multiple results if there are any.
I was able to get python to return the first result ok, but then it stops. I got around the csv thing by using a hash command and .split (I would rather read it as a csv although I couldn't get it to work.) I had to edit the external file so instad of the data being seperated by commas it was seperated by semicolons, which is not ideal as I am not supposed to be messing with the supplied file.
Anyhow...
My external file looks like this:
roombookings.txt
6-3-07;L1;MSW001;1
6-3-07;L2;MSP201;1
6-3-07;L3;WEB201;1
6-3-07;L4;WEB101;1
6-3-07;L5;WEB101;1
7-3-07;L1;MSW001;2
7-3-07;L2;MSP201;2
7-3-07;L3;WEB201;2
7-3-07;L4;WEB101;2
7-3-07;L5;WEB101;2
8-3-07;L1;WEB101;1
8-3-07;L2;MSP201;3
Here's what my code looks like:
roomNumber = (input("Enter the room number: "))
def find_details(id2find):
rb_text = open('roombookings.txt', 'r')
each_line = rb_text.readline()
while each_line != '':
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = each_line.split(";")
if id2find == (s['Room']):
rb_text.close()
return(s)
each_line = rb_text.readline()
rb_text.close()
room = find_details(roomNumber)
if room:
print("Date: " + room['Date'])
print("Room: " + room['Room'])
print("Course: " + room['Course'])
print("Stage: " + room['Stage'])
If i run the program, I get prompted for a room number. If I enter, say, "L1"
I get:
Date: 6-3-07
Room: L1
Course: MSW001
Stage: 1
I should get 3 positive matches. I guess my loop is broken? Please help me save my sanity!
Edit. I've tried the solutions here but keeps either crashing the program (I guess I'm not closing the file properly?) or giving me errors. I've seriously been trying to sort this for 2 days and keep in mind I'm at a VERY basic level. I've read multiple textbooks and done many Google searches but it's all still beyond me, I'm afraid. I appreciate the assistance though.
Your code does "return(s)" the first time the "id2find" argument is exactly equal to the room.
If you want multiple matches, you could create an empty list before entering the loop, append every match to the list WITHOUT returning, return the list, and then use a for-loop to print out each match.
First. For iterating over lines in the file use next:
for line in rb_text:
# do something
Second. Your function returns after first match. How can it match more then one record? Maybe you need something like:
def find_details(id2find):
rb_text = open('roombookings.txt', 'r')
for line in rb_text:
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(";")
if id2find == (s['Room']):
yield s
rb_text.close()
And then:
for room in find_details(roomNumber):
print("Date: " + room['Date'])
print("Room: " + room['Room'])
print("Course: " + room['Course'])
print("Stage: " + room['Stage'])
And yes, you better use some CSV parser.
Your problem is the return(s) in find_details(). As soon as you have found an entry, you are leaving the function. You do not even close the file then. One solution is to use an empty list at the beginning, e.g results = [], and then append all entries which matches your requirements (results.append(s)).

Categories

Resources