Editing user-input string values in Python - 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

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.

Conversion Program

I have a program where I need to prompt the user for an input of a word and a key. Next, the program should remove all the spaces, punctuation and all numbers from the word and convert all the letters into uppercase. Once that is done I need the program to replace all the characters of the word with the key. So if the word is a library, and the key is moose, the program should print out moosemo. I know that this part includes something like append.key(len plaintext) something of this fashion, but I'm not exactly sure how. I don't have a lot of the code done because I am pretty lost. Here is what I have so far:
phrase = input("Please enter the phrase to be encrypted: ") #prompt user for phrase
encryptionkey = input("Please enter the key: ") #prompt user for encryption key
print(phrase.upper()) #converts all characters from phrase to uppercase
If anyone knows what to do or what to change, please let me know. Please show the change in code with your response. Thanks in advance
I used answers from here and here to make compose this.
Here is one way you might do it, using the string class to get rid of punctuation and numbers.
import string
phrase = input("Please enter the phrase to be encrypted: ") #prompt user for phrase
encryptionkey = input("Please enter the key: ") #prompt user for encryption key
#replace - gets rid of spaces
#first translate - gets rid of punctuation
#second translate - gets rid of digits
#upper - capitalizes.
phrase = phrase.replace(" ", "")\
.translate(str.maketrans('', '', string.punctuation))\
.translate(str.maketrans('','',string.digits))\
.upper()
times_to_repeat = len(phrase)//len(encryptionkey)
leftover_length = len(phrase)%len(encryptionkey)
#multiply string by how many times longer it is than the encryption, then add remaining length.
#in python you can do 'string'*2 to get 'stringstring'
final_phrase = encryptionkey*times_to_repeat+encryptionkey[:leftover_length]
print(final_phrase)
Output:
# Only keep the alphabet characters
phrase = ''.join(c for c in phrase if c.isalpha())
# Add the encryption key at least 1 more times than divisible (to count for remainder)
# and slice the output to the length needed
phrase = (encryptionkey * (1 + len(phrase) // len(encryptionkey)) [:len(phrase)]

How to keep a variable in a string from changing 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)

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

Python Encryption

So for an exam question I've followed this specific pseudo code which basically makes a program which encrypts a number sequence using the same principle as the ceasar cipher. It should work but for some reason it returns the error.
TypeError: 'int' object is not iterable
Heres the code, i hope you guys can help me, much appreciated
plainNum = input("enter a number to encode ")
codedNum = ' '
Key = input("enter a key ")
for i in plainNum:
codedNum = codedNum + str((int(i)+key)%10)
print codedNum
Use raw_input if you expect a string:
plainNum = raw_input("enter a number to encode ")
input() interprets the input as if it is Python code; enter 5 and it'll return an integer, enter 'some text' (with quotes) and it'll return a string. raw_input() on the other hand returns the entered input uninterpreted.
Most dirty fix of all, simply change
for i in plainNum:
with
for i in str(plainNum):
This is working but not if I use a decimal and it doesn't behave if I enter words or spaces. Consider checking first that the entry is a number with something like:
try:
float(element)
except ValueError:
print "Not a float"
after stripping any whitespace with something like:
plainNum = plainNum.strip()
But this outputs the encoded digits of your entered integer:
plainNum = raw_input("enter a number to encode ")
codedNum = ' '
key = input("enter a key ")
for i in plainNum:
codedNum = codedNum + str((int(i)+key)%10)
print codedNum
Ask the user for the number with raw_input. This makes the input a string which you can iterate over with:
for char in plainNum:
Yes, this is a now a char in a string and so you've used the int(i) function.
you maybe also wanna change key to Key to reflect what variable is declared
and also make codeNum initially equal to '' instead of ' ' (no space vs space)
just book keeping stuff

Categories

Resources