Error trying to replace spaces with underscores - python

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

Related

How do you store a list of strings in an index function?

sentence = input("Input sentence: ")
punctuation = [" ", ",", ".", ":", "?", "!"]
interruption1 = sentence.index(punctuation)
word1 = sentence[:interruption1]
print(word1)
In this question, the main aim is to have the program print the first word that the user types by identifying a character that implies the first word has ended (the punctuation characters in the 'punctuation' variable). I want the program to accept the 'punctuation' variable within the index function but it sends an error message saying "must be str, not list". I tried for loops, they don't work here either as far as I know.
A previous question of mine gave me information that you can't use boolean values to represent a set of values in a variable, so I used a list, but now this error happens, and there is absolutely nothing on the Internet on this sort of problem (neither do I have an IT teacher or any friends that do Python), so I had to come here after about an hour of trying random combinations of code. How do I make Python accept the list and use it inside the index function? Thank you.
You don't need to use an index unless it is demanded; just keep accepting characters from the sentence until you come to a punctuation. So the simplest looping approach is:
sentence = input("Input sentence: ")
punctuation = [" ", ",", ".", ":", "?", "!"]
result = ""
for c in sentence:
if c in punctuation:
break
else:
result = result + c
print(result)
To be honest this is something you should do with regular expressions. But, that doesn't really answer your question, so - you are close, but your problem is that you're passing a list of strings instead of a single string, as your error message implies.
You should loop through each string in the list and get the first occurrence of the string in your sentence. You can use str.index() but I prefer to use str.find() which will return a -1 if the character is not found thus we don't have to mess around with error exceptions.
sentence = input("Input sentence: ")
punctuation = [" ", ",", ".", ":", "?", "!"]
matches = []
for character in punctuation:
match = sentence.find(character)
#If the character is found, save to a separate list.
#No match means value is -1, so ignore it using >0
if match >0:
matches.append(match)
# Now find the match that occurs first:
first_match_index = min(matches)
# Return first word
first_word = sentence[:first_match_index]
print(first_word)
How do I make Python accept the list and use it inside the index function?
You can't str.index only accepts str.
I tried for loops, they don't work
A for loop could work
iterate over sentence while keeping track of the index
for each character check to see if it is in punctuation
if it isn't in punctuation
continue with the next character
if it is in punctuation
use the index to extract the first word using a slice: sentance[:index]
stop iterating

How to capitalize the first letter of a user-inputted string but keep the rest of the string's capitalization

Basically as the title says, I want the sentences of the user input to be capitalized, but not lose their capitalization in the process. The input's supposed to be two sentences that get separated by periods. The code I have here outputs them the sentences, but not joined or keeping the rest of the capitalization.
def main():
user_input = input("Enter the sentence you would like to be modified!: ").split(". ")
capitalized_sentences = [user_input[0].upper() + user_input[1:] for sentence in user_input]
recombined_sentences = ". ".join(capitalized_sentences)
Just edit the first character of each split to be upper:
# For this example, lets use this string. However, you would still use
# user_input = input("...") in your actual code
user_input = "for bar. egg spam."
# Turn the user_input into sentences.
# Note, this is assuming the user only is using one space.
# This gives us ["foo bar", "egg spam"]
sentences = user_input.split(". ")
# This is called a list comprehension. It's a way of writing
# a for-loop in Python. There's tons of documentation on it
# if you Google it.
#
# In this loop, the loop variable is "sentence". Please be mindful
# that it is a singular form of the word sentences.
#
# sentence[0].upper() will make the first letter in sentence uppercase
# sentence[1:] is the remaining letters, unmodified
#
# For the first iteration, this becomes:
# "f".upper() + "oo bar"
# "F" + "oo bar"
# "Foo bar"
capitalized_sentences = [sentence[0].upper() + sentence[1:]
for sentence
in sentences]
# At this point we have ["Foo bar", "Egg spam"]
# We need to join them together. Just use the same ". " we
# used to split them in the beginning!
#
# This gives us "Foo bar. Egg spam."
recombined_sentences = ". ".join(capitalized_sentences)
Replace "sentences" with your user_input bit
Note, there might be a "gotcha" if the user inputs sentences of a format you aren't expecting. For example, what if the user entered two spaces instead of one? Then the above code would try to capitalize a whitespace character. You would need to account for that.
It's very simple: You can use the String method upper() on a part of the string.
Here is a one-liner to do just that:
CapWord = "".join([c.upper() if i == 0 else c for i, c in enumerate([j for j in rawWord])])
Just replace CapWord and rawWord with respective values (you can change them to sentences / words depending on what you want to do.
What it does:
Iterates over an array with all the characters in the string and their respective enumeration (to avoid duplicate letters being capitalised as well) then checks if the char (c) has a number corresponding to the indexes to capitalise, and is converted to a string.

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)) )

title() method in python writing functions when word like aren't

using function
def make_cap(sentence):
return sentence.title()
tryining out
make_cap("hello world")
'Hello World'
# it workd but when I have world like "aren't" and 'isn't". how to write function for that
a = "I haven't worked hard"
make_cap(a)
"This Isn'T A Right Thing" # it's wrong I am aware of \ for isn\'t but confused how to include it in function
This should work:
def make_cap(sentence):
return " ".join(word[0].title() + (word[1:] if len(word) > 1 else "") for word in sentence.split(" "))
It manually splits the word by spaces (and not by any other character), and then capitalizes the first letter of each token. It does this by separating that first letter out, capitalizing it, and then concatenating the rest of the word. I used a ternary if statement to avoid an IndexError if the word is only one letter long.
Use .capwords() from the string library.
import string
def make_cap(sentence):
return string.capwords(sentence)
Demo: https://repl.it/repls/BlankMysteriousMenus
I found this method to be very helpful for formatting all different types of texts as titles.
from string import capwords
text = "I can't go to the USA due to budget concerns"
title = ' '.join([capwords(w) if w.islower() else w for w in text.split()])
print(title) # I Can't Go To The USA Due To Budget Concerns

Python coding flaw for making acronyms

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

Categories

Resources