IncognitoBatman IncognitoBatman - 25 days ago 8
Python Question

Python:Taking the first character without Lists

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. I don't know what to do now after what I have 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)

Answer

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