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)) )
Related
I am trying to ask the player to write a sentence. If the sentence has no spaces, it will return as so. Otherwise, i want all the spaces to be replaced with underscores.
sentence = input("Enter de sentence: ")
def replace():
if sentence.count(" ")>0:
sentence[1 : sentence.index(" ")] +"_"+ sentence[sentence.index(" ")+1 : len(sentence)]
else:
return replace()
print(replace)
print(replace)
no matter what i enter after "Enter de sentence:" is asked, i get this returned:
<function replace at 0x7fecbc2b2280>
I have tried looking up some of the refences for some of the code and tried to change some of the variables, but to no avail.
You're misunderstanding many thing it seems, the method name, the variables, ...
Let's go back to a simple one
def replace(content):
if content.count(" ") > 0:
content = content.replace(" ", "_")
return content
sentence = input("Enter de sentence: ")
print(replace(sentence))
But that example is too much verbose, only to explain you how it works, in fact, you don't need to check if there is spaces or not, just use str.replace
def no_space(content):
return content.replace(" ", "_")
sentence = input("Enter de sentence: ")
print(no_space(sentence))
it's just to mention, that the required task can also be done like this:
we separate the input text by using .split() method. this creates a list of individual words.
finally we need to re-combine the elements of the list to the final string by using '_'.join() with an underscore as an argument.
this can be done as a function or directly in the code.
sentence = input().split()
print('_'.join(sentence))
replace() is already a built-in method for string operation.
It will be simle as:
sentence = input("Enter de sentence: ").replace(' ','_')
print(sentence)
# Enter de sentence: I want to go to school
# I_want_to_go_to_school
But if you want to create custom replace function, your function should receive parameter to pass input strings as argument. In function, initialize a new empty string to store the result, then use for loop to iterate each string in sentence. If string is spaces assign it to underscore and concat to a new string. Lastly return the new string.
sentence = input("Enter de sentence: ")
def replaces(sentence):
new = str()
for i in sentence:
if i == ' ':
i = '_'
new += i
else:
new += i
return new
print(replaces(sentence))
# Enter de sentence: I want to go to school
# I_want_to_go_to_school
I have a task to rearrange a name to last first middle initial. I know for this I can use split() but I'm trying to understand it the way I'm learning it right now which is index and find ect to rearrange it. My question is how would I make it so the program knows what is the first last and middle names since it changes depending on user input. I've tried this and it doesn't work. Is there a way to do this?
Name = input("Enter a name like 'First I. Last: ")
words = Name.find(" ")
first, middle, last = words[1], words[0], words[-1]
find will return the index into a string of that occurence, you can then use that index to slice your original string, find also takes an optional second index to tell it where to start searching from ...
Name = input("Enter a name like 'First I. Last: ")
first_space_index = Name.find(" ")
first_name = Name[:first_space_index]
# find the first space that comes after first_space_index
second_space_index = Name.find(" ",first_space_index + 1)
middle_initial = Name[first_space_index+1:second_space_index]
this is not nearly as good of a solution as just using split but meh ...
You can use the string.split() function to gather the different words in the input. This is preferable to using string.find() as you do not have to slice to find the answer.
name = input("Enter a name like 'First I. Last: ")
words = name.split()
first, middle, last = name[0], name[1], name[2]
Then you can work out the first letter of each 'Hello'[0] -> 'H'
string = input('Please enter a string: ')
replaced_string = string.replace(string[0],'e')
replaced_string[0] = string[0]
print(replaced_string)
I tried to replace all the letters of the first char in the string but keep the first char as it was, but apparently my code doesn't work on the third line. Can you suggest a solution how to replace it?
You could do it like this:
input_str = input()
first_letter = input_str[0]
rest_of_letters = input_str[1:]
# Take the first letter, and append it the rest of the letters, but
# with "e" replaced by the first letter.
replaced_string = first_letter + rest_of_letters.replace(first_letter, 'e')
The key problem with how you tried to do it is strings are immutable. You can't do my_str[0] = "a". If you want to modify a string you must create a new string with the modifications you want.
I am not getting what you want to do. but Strings do not support item assignment.
The code written below should give results like below. For example, if input is ' Lion head and Snake tail', output should be - 'LHAST'.
Instead the result is 'LLLLL'. Please check my code. If possible please suggest better practice and help me with better code.
Code is as follows:
#ask for Input
name = input('Input words to make acroname :')
#make all in caps
name = name.upper()
#turn them in list
listname = name.split()
#cycle through
for namee in listname:
#Get the first letter & type in same line
print(name[0],end="")
print()
input (' press a key to move out' )
You may correct your code. Instead of print(name[0]) you should use print(namee[0]) as you want to print the first letter of the word, not the original name.
A good practice is to name the variables the more descriptive you can so as to avoid such typos.
If you want to print the acronym in same line I would suggest to use below code to get variable acronym with the desired output:
phrase = raw_input('Input words to make acronym:')
phrase = phrase.upper()
list_words = phrase.split()
acronym = [word[0] for word in list_words]
acronym = "".join(acronym)
print acronym
You could use str.join with a generator-expression for a one-line solution to the problem:
>>> name = "Lion head and Snake tail"
>>> ''.join(i[0].upper() for i in name.split())
'LHAST'
why?
Well if we start from inside the generator, we are iterating through name.split(). The .split method of a str returns a list of all the different strings which have been found by splitting on what is passed into the method. The default character is a space and since we want the words, this is fine for us.
We then say that for each word i in this list, take the first character from the string with: i[0]. We then convert this to upper case with str.upper().
Then, the final step is to join all these characters together and that is done with the str.join method.
Simply:
print ''.join([P[0] for P in input('Input words to make acroname :').upper().split()])
Use input('') for python 3 and raw_input('') for python 2
I've searched answers on here and tried implementing them but I think that there is some tiny detail I'm missing. I have a very short python code for a program that is supposed to return the initials with periods of a persons input(for their full name). So for example, input is Atticus Leonard Beasley and output should be
A.L.B.
but instead I'm getting:
A.
L.
B.
Here's my code:
def main():
full_name = input("Enter your first, middle, and last name: ")
for ch in full_name:
if ch.isupper():
ch = ch.rstrip('\n')
print (ch,'.', sep='')
main()
FYI, you can do this using split and join:
def main():
full_name = input("Enter your first, middle, and last name: ")
initials = []
for name in full_name.split():
initials.append(name[0])
print('.'.join(initials) + '.')
main()
Or using list comprehension:
def main():
full_name = input("Enter your first, middle, and last name: ")
print('.'.join(name[0] for name in full_name.split())+'.')
main()
I think you can do that in a easier and "more pythonic" way.
full_name = input("Enter your first, middle, and last name: ")
print(''.join([ch[0].upper() + '.' for ch in full_name.split()]))
EXPLANATIONS
Instead of doing a for loop over each letters of the name, you can use split() function to be sure to took care of every words without the extra spaces.
sentence = "hello world"
for ch in sentence.split():
print(ch) # hello
break
Now, you try to verify if the first letter is an uppercase, but if the user enter his name without uppercase, your function does not work. An easier solution will be to extract the first letter of the word ch[0] and automatically add an uppercase: ch[0].upper()
Maybe the one-liner solution is confusing, but most of the python developers use list comprehension over for loops when the solution is easily readable.
EDIT
One more thing, even if you are writing a simple function such as print the initials of a name, you should always write tests accordingly.
A good way to start is to use doctests because it forces you to describe what your function does. Even if you think it's a waste of times, it helps to overcome many problems when your program is getting bigger. I'd be please to help you if you want to try to write your first doctest