我的代码是关于使用每个单词/数字的第一个字符/数字作为句子/短语中的字符来创建密码,并将其打印出来。
示例:停止并闻到350"玫瑰"。 - > Sast3r。 (忽略 引用使用r代替)
使用列表会很容易,但是在我的代码的分配中你不能使用它们。所以,到目前为止,我还不知道该怎么做
功能:
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
主:
# Imports
from credentials import create_password
# Inputs
phrase = str(input("Enter a sentence or phrase: "))
# Outputs
password = create_password(phrase)
print(password)
答案 0 :(得分:2)
我认为通过整个短语而不用担心分裂空间更为直接。而是跟踪你是否刚刚看到一个空间。您只想在看到空格后添加角色。
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)
输出:
Sast3r
答案 1 :(得分:1)
你肯定是在正确的轨道上!使用str.find()
方法绝对是可行的方法!
但是,您需要了解str.find()
方法的作用。签名:
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.
在不告诉函数从哪里开始的情况下,它总是会在字符串中找到第一个出现的字符。它不会知道你正在浏览字符串的每个字符。
所以让我们稍微改变一下:
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]
希望这可以获得您想要的密码。
答案 2 :(得分:1)
优先使用内置函数,例如,每次找到空间的位置时,为什么不直接按照spilled函数的空间,使字符串直接到字符列表,每个element是一个单词,然后删除列表中的每个元素。
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)
答案 3 :(得分:-2)
尝试获取字符串中的第一个字符,然后是空格后面的每个字符。看起来你有正确的想法。