Python:Taking the first character without Lists - python

My code is about creating a password using the first character/digit of every word/number as a character in a sentence/phrase and printing it just as so.
Example: Stop and smell the 350 "roses". -> Sast3r. (Ignoring
quotations using r instead)
This would be very easy using lists, but you cannot use them in this assignment for my code. So, I don't know what to do now after what I have done so far
Function:
def create_password(phrase):
q = "'" # quotations
dq = '"' # double quotes
password = phrase[0]
for i in phrase:
x = phrase.find(" ")
if i.isalnum:
password += phrase[x + 1]
elif x == q or x == dq:
password += phrase[x + 2]
return password
Main:
# Imports
from credentials import create_password
# Inputs
phrase = str(input("Enter a sentence or phrase: "))
# Outputs
password = create_password(phrase)
print(password)

I think it is more straightforward to walk through the entire phrase without worrying about splitting on spaces. Instead keep track of whether or not you've just seen a space. You only want to add the character after just seeing a space.
def create_password(phrase):
q = "'" # quotations
dq = '"' # double quotes
#Initialize the password to be an empty string
password = ""
#We are at the start of a new word (want to add first index to password)
new_word = True
#Walk through every character in the phrase
for char in phrase:
#We only want to add char to password if the following is all true:
#(1) It's a letter or number
#(2) It's at the start of a new word
#(3) It's not a single quote
#(4) It's not a double quote
if char.isalnum and new_word:
if char != q and char != dq:
password += char
new_word = False #<-- After adding char, we are not at a new word
#If we see a space then we are going to be at a new word
elif char == " ":
new_word = True
return password
p = create_password('Stop and smell the 350 "roses"')
print(p)
Output:
Sast3r

You're definitely on the right track! Using the str.find() method is definitely the way to go!
However, you need to understand what the str.find() method does. Look at the signature:
str.find(sub [,start [,end) -> int
# sub -> character to find
# start -> where the function should start looking in the string
# end -> where the function should stop looking
# Returns a number, which is the place it found the character.
# If it didn't find anything, then return -1.
Without telling the function where to start, it will always find the first occurrence of the character in the string. It won't know that you're going through each character of the string.
So let's change it up a little bit:
for char_index in xrange(len(phrase)):
# Tell the method to look after char_index: we've already looked before this!
x = phrase.find(' ', char_index) index
if phrase[x+1].isalnum(): # It's a function, notice the brackets?
password += phrase[x + 1]
elif phrase[x+2] == q or phrase[x+2] == dq:
password += phrase[x + 2]
Hopefully, this should get your desired password.

Give priority to the use of built-in function, for example, every time you find the location of space, then why not directly in accordance with the space for spilt function, so that the string directly to the character list, each element is a word, and then remove each element in the list.
def create_password(phrase):
password = ''
phrase_list = phrase.split(' ')
print (phrase_list)
for i in phrase_list:
print (i[0])
password += i[0]
return password
if __name__ == '__main__':
# Inputs
phrase = str(input("Enter a sentence or phrase: "))
# Outputs
password = create_password(phrase)
print(password)

Try taking the first character in the string, and then every character that follows a space. It looks like you have the right idea.

Related

how to extract a sentence from string in python using simple for loop?

str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
Like I want to extract I Love Python from this string. But I am not getting how to.
I tried to loop in str1 but not successful.
i = str1 .index("I")
for letter in range(i, len(mystery11)):
if letter != " ":
letter = letter+2
else:
letter = letter+3
print(mystery11[letter], end = "")
In your for loop letter is an integer. In the the first line of the loop you need to compare mystery[11] with " ":
if mystery11[letter] != " ":
You can use a dict here, and have char->freq mapping of the sentence in it and create a hash table.
After that you can simply iterate over the string and check if the character is present in the hash or not, and if it is present then check if its count is greater than 1 or not.
Don't know if this will solve all your problems, but you're running your loop over the indices of the string, This means that your variable letter is an integer not a char. Then, letter != " " is always true. To select the current letter you need to do string[letter]. For example,
if mystery11[letter] != " ":
...
Here's how I'd go about:
Understand the pattern of the input: words are separated by blank spaces and we should get every other letter after the first uppercase one.
Convert string into a list;
Find the first uppercase letter of each element and add one so we are indexing the next one;
Get every other char from each word;
Join the list back into a string;
Print :D
Here's the code:
def first_uppercase(str):
for i in range(0, len(str)):
if word[i].istitle():
return i
return -1
def decode_every_other(str, i):
return word[i::2]
str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
# 1
sentence = str1.split()
clean_sentence = []
for word in sentence:
# 2
start = first_uppercase(word) + 1
# 3
clean_sentence.append(decode_every_other(word, start))
# 4
clean_sentence = ' '.join(clean_sentence)
print("Input: " + str1)
print("Output: " + clean_sentence)
This is what I ended up with:
Input: srbGIE JLWokvQeR DPhyItWhYolnz
Output: I Love Python
I've added some links to the steps so you can read more if you want to.
def split(word):
return [char for char in word]
a = input("Enter the original string to match:- ")
b = input("Enter the string to lookup for:- ")
c = split(a)
d = split(b)
e = []
for i in c:
if i in d:
e.append(i)
if e == c:
final_string = "".join(e)
print("Congrats!! It's there and here it is:- ", final_string)
else:
print("Sorry, the string is not present there!!")

String Index out of Range - Python 3.x.x with swapcase() function

I am trying to capitalize every other letter of a string which is given by and input. For some reason it give me the error 'string index out of range' and i have no idea why! the range is set from 0 to the length of the string so that cant be possible i thought!
s = input('Please enter a string: ')
p=s.lower()
o=s.upper()
q=p
k=len(s)
l=1
for x in range(0,k):
if l%2==0:
q=q[x].swapcase()
l+=1
else:
l+=1
print(q)
When you do this:
q=q[x].swapcase()
q becomes a single letter.
The next time around you try:
q[1]
but there is no q[1] because you made it a single letter.
This is one of several reasons why python encourages you to avoid creating index variables and instead looping over the items themselves. If you do that and give your variables more descriptive names, these kind of error are easier to catch. For example:
s = input('Please enter a string: ')
lower_case = s.lower()
new_string = ""
for index, letter in enumerate(lower_case):
if index % 2 == 0:
new_string += letter.swapcase()
else:
new_string += letter
print(new_string)

Replacing part of a string using a For loop

I need to get a user to enter a sentence for an assignment. Using a for loop, I then need to replace all spaces with %20 in order to prep the string to be used as a URL. I cannot for the life of me figure it out.
sentence = str(input("Please enter sentence:"))
space = (" ")
for space in sentence:
space.replace(sentence, space, "%20", 500)
print(sentence)
This is what I have entered so far but it is completely wrong.
String in Python can't be modified. The replace() function returns a new string with all the replacements done. You need to assign this result somewhere. So you can do:
sentence = sentence.replace(" ", "%20")
If you want to do it with a loop, you need to build the result in another variable.
new_sentence = ""
for char in sentence:
if char == " ":
new_sentence += "%20"
else:
new_sentence += char
There's no point in using replace() in the loop.
Replace everything after the first line with print(sentence.replace(" ","%20"))
or, if you really must use a loop:
s = ''
for x in sentence:
if x == ' ':
s += "%20"
else:
s += x
print(s)
you've got a few problems here:
the variable space that you define before the loop is equal to " " but then you're using the same name for the for loop variable, which is going to iterate through the string the sentence string, in the loop, it's going to use the value defined by the loop.
You're giving the replace method too many arguments, it's a method of the string object so you don't need to pass it the large string to operate on Replace Method
You're using the replace method on the space string and not on the sentence string
Good way to do it in real life:
old = ' '
new = '%20'
sentence = str(input("Please enter sentence:"))
print(sentence.replace(old,new))
The way your teacher is probably after:
sentence = str(input("Please enter sentence:"))
old = ' '
new = '%20'
newSentence = ''
for letter in sentence:
if letter == ' ':
newSentence += new
else:
newSentence += letter
print(newSentence)

altering a word encoder and decoder to give recognize spaces and punctuation

The 2nd function encodes a word phase and the 3rd one decodes that same word function but it doesn't skip over the spaces and punctuation.
def buildCipher(key):
alpha="abcdefghijklmnopqrstuvwxyz"
rest = ""
for letter in alpha:
if not(letter in key):
rest = rest + letter
print key+rest
def encode(string,keyletters):
alpha="abcdefghijklmnopqrstuvwxyz"
secret = ""
for letter in string:
index = alpha.find(letter)
secret = secret+keyletters[index]
print secret
def decode(secret,keyletters):
alpha="abcdefghijklmnopqrstuvwxyz"
clear = ""
for letter in secret:
index = keyletters.find(letter)
clear = clear+alpha[index]
encode("this is zest!!!" , "earthbcdfgijklmnopqsuvwxyz")
#gives me sdfqfqzhqs
#need it to give me sdfq fq zhqs!!!
decode("tdfq fq zhqs!!!" , "earthbcdfgijklmnopqsuvwxyz")
At the moment the space character isn't in either alpha or your keyletters - if you don't want space encrypted then add it in the same position in both.
NOTE your code currently ignores the fact that space is in the string to encode but not in the keyletters. It would be a good idea to be explicit about this in your code - check that the letter is present rather than simply ignoring the error.
What happens if letter isn't alphabetic? Exactly, it doesn't get added since it can't find it's index in alpha. You need to have an if/else statement:
def encode(string,keyletters):
alpha="abcdefghijklmnopqrstuvwxyz"
secret = ""
for letter in string:
if letter in alpha:
index = alpha.find(letter)
secret = secret+keyletters[index]
else:
secret = secret + letter
print secret

How do I make it so the code only shifts the letters and not the space?

#get string and shift from user
string = input('Please enter a string to be ciphered: ')
shift = input('Please enter a shift amount between 0 and 25: ')
#strings are immutable so it must be converted to a list
s=list(string)
#now this will convert each character based on the shift
for i in range(0,len(s)):
s[i]=chr(ord(s[i]) + int(shift))
print ("".join(s))
You should call the method str.alpha to ensure that the chosen element is an alphabet before shifting
for i in range(0,len(s)):
if elem.isaplha():
s[i]=chr(ord(s[i]) + int(shift))
On a second though, you are doing to much work here. Why not use a comprehension expression?
s = ''.join(chr(ord(elem) + shift) if elem.isalpha() else elem for elem in s)
or if you are adventurous enough
s = ''.join([elem, chr(ord(elem) + shift)][elem.isalpha()] for elem in s)
and finally have you checked the string.makestrans along with str.translate to do the conversion?
from string import maketrans, ascii_alpha
s = s.translate(maketrans(ascii_alpha[shift:] + string.ascii_alpha[:shift])
All you have to do is check if the current character is not one you want to skip.
for i in range(0,len(s)):
#If not a space, cipher this character.
if s[i] != ' ':
s[i]=chr(ord(s[i]) + int(shift))
There is however, a possibility that one of your characters will be ciphered to a space, in which case that character would be skipped when reversing the cipher.
Also, a simple cipher like this should not be considered secure in the least.

Categories