How to keep a variable in a string from changing python - python

I'm new to python and I've got an assignment to Write a program that inputs a string from the user and than to print the string in which all instances of the first character have been replaced by an 'e' except for the first character itself.
This is what I got so far:
sent = input('Please enter a string: ')
var1 = sent[0]
var2 = 'e'
mod_sent = sent.replace(var1,var2)
print(mod_sent)
I know that nothing there is supposed to keep the first character from changing but I feel like I have tried everything and just have to delete because it is not working.
Would like an explanation and just an answer if possible please.

Actually, the first character is changing in the sent.replace you called, because python replaces every character in the string with the substitute.
You can just revert the first character, which should be easy since you stored it in var1 (try using more descriptive names next time).
mod_sent = var1 + mod_sent[1:]
Add this before your print statement and it should work.

You can slice the string str[1:] will return the whole string except first character:
sent = input('Please enter a string: ')
var1 = sent[0]
var2 = 'e'
mod_sent = var1 + sent[1:].replace(var1,var2)
print(mod_sent)

Related

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

How to make sure the function turns what I write into a string

Here's the code:
abc = ['abcdefghijklmnopqrstuvwxyz', 'secondstring', 'thirdstring']
def findletter(letter, l1st, idx):
if letter in l1st[idx]:
print("found")
else:
print("not found")
findletter("i", abc, 0)
This works, however I have a few questions:
Why writing the letter the 'i' without quotation marks gives an error?
How do I make so it'd take letters without quotation marks?
Thanks.
A "letters without quotation marks" would be a variable.
If you set that variable to a string first, it will work without errors.
i = "something"
findletter(i, abc, 0)
Otherwise it's un undeclared variable, which is an error.
Writing i without quotations considers it as a variable which i has not been assigned to
For the second, str(abc) would work as str() converts what you have to a string
If you write "i" without the quotation marks, it will take it as a variable instead of a string.
If you do not want to hard-code what you to search, try this:
abc = ['abcdefghijklmnopqrstuvwxyz', 'secondstring', 'thirdstring']
def findletter(letter, l1st, idx):
if letter in l1st[idx]:
print("found")
else:
print("not found")
i = input("Enter the string to be searched: ")
findletter(i, abc, 0)
This will ask you what to search in the shell, every time you run the code and input() function always returns the value as a string.

How to swap values in strings without loop

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.

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

raw_input check to allow for reinitiation of same function

I was banging my head against my desk on this one, because I'm an idiot, and I've finally gotten it to work. This is a simplified, dumb version of my actual code (which is why the function's purpose seems so inane) but I'm curious whether there is (or rather, am sure there must be) a more efficient way of doing the following:
def get_char():
character = raw_input("Enter the character you would like to use.\n >")
if character.isalpha:
proceed = raw_input("The value entered is " + character + "\nWould you like to proceed?(Y/N)\n>")
while True:
if proceed in "N,n":
raw_input("Press enter to try again with another value.")
character = get_char()
break
else:
break
return character
#print character
character = get_char()
print character
What I want to end up with is a way of checking that the user's input is what they intended. Until I set character = get_char() in the while loop, I was getting problematic output (i.e. incorrect final values for character); having fixed that, I've noticed that if I include the print statement at the end of the get_char() definition, it prints out the number of times a "no" choice has been made +1. While the end result is still fine, I'm curious whether the fact that it seems to be holding iterations in a queue, as indicated by the multiple prints upon inclusion of the print statement, means that there's a better way of doing this. Thanks in advance for any help!
UPDATE:
Just in case anyone else needs help with this same issue, based on the suggestion by millerdev, I've adjusted the code to the following, which works just the same except without the self-call which was generating unnecessary character queuing:
def get_char():
while True:
character = raw_input("Enter the character you would like to use\n >")
if character.isalpha:
proceed = raw_input("The value entered is " + character + "\nWould you like to proceed? (Y/N)\n>")
if proceed in ("N", "n"):
raw_input("Press enter to try again with another value.")
else:
break
#print character
return character
character = get_char()
Because of character = get_char(), your loop only runs once, because it will recurse deeper if it fails instead of iterating again. This probably isn't what you want, because it's slower and runs the risk of overflowing the stack. The cleanest way to do this would probably be (you could replace my messages with yours easily):
def get_char(is_valid = lambda c: True):
while True:
c = raw_input('enter a character > ')
if is_valid(c):
keep = raw_input('do you want to use {0}? (Y/N)> '.format(c)).lower()
if 'n' in keep:
continue # go back to While True line
return c
print('{0} is not a valid character'.format(c))
Session:
>>> get_char()
enter a character > a
do you want to use a? (Y/N)> n
enter a character > c
do you want to use c? (Y/N)> no
enter a character > x
do you want to use x? (Y/N)> y
'x'
At least, this is the cleanest in my opinion. Your implementation has a few other problems, like proceed in "N,n", which would also count comma as an n, and if the character isn't isalpha, you still return it.
Is this what you're aiming for?
def get_char():
while True:
character = raw_input("Enter the character you would like to use.\n >")
if character.isalpha: # this is always true; add parens if that's what you want, otherwise remove it
proceed = raw_input("The value entered is " + character + "\nWould you like to proceed? (Y/n)\n>")
if proceed.lower() == "n":
raw_input("Press enter to try again with another value.")
character = get_char()
return character
character = get_char()
print character

Categories

Resources