Sast3-6ren">
gpt4 book ai didi

Python:在没有列表的情况下取第一个字符

转载 作者:行者123 更新时间:2023-12-01 03:33:21 25 4
gpt4 key购买 nike

我的代码是关于使用每个单词/数字的第一个字符/数字作为句子/短语中的字符来创建密码,并按原样打印它。

Example: Stop and smell the 350 "roses". -> Sast3r. (Ignoring quotations using r instead)

使用列表会非常容易,但您不能在我的代码的作业中使用它们。所以,在我做了这么多事情之后,我现在不知道该怎么办

功能:

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)

最佳答案

我认为遍历整个短语更直接,而不必担心空格分割。相反,请跟踪您是否刚刚看到过一个空间。您只想在看到空格后添加字符。

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

关于Python:在没有列表的情况下取第一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40622453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com