Python 检查昵称时如何检查数组中的每个元素
所以基本上我在python上写一个程序,我需要的一个子例程是没有重复的昵称,所以我所做的是将所有的昵称添加到一个txt文件中,然后我想读取该文件,并确保昵称与文件中的昵称不同。代码如下:Python 检查昵称时如何检查数组中的每个元素,python,Python,所以基本上我在python上写一个程序,我需要的一个子例程是没有重复的昵称,所以我所做的是将所有的昵称添加到一个txt文件中,然后我想读取该文件,并确保昵称与文件中的昵称不同。代码如下: sAskNick = input ("What nickname would you like to proceed with?: ") nicknames = open("nicknames.txt","a+") aAllNicks = [] with open ("nicknames.txt") as
sAskNick = input ("What nickname would you like to proceed with?: ")
nicknames = open("nicknames.txt","a+")
aAllNicks = []
with open ("nicknames.txt") as f:
aAllNicks = f.read().splitlines()
for i in range(0,4):
while sAskNick == aAllNicks[i]:
print("Nickname used/inappropriate")
else:
print("Valid nickname")
break
在这种情况下,昵称.txt仅在每行中包含一个昵称列表,文件中有5个昵称。如果您想在给定昵称位于该文件中时执行某些操作:
given_nickname = input('What is your nickname?')
#Read the file:
nicknames = open(r'c:\filelocation','r').read().splitlines()
for element in range(len(nicknames)):
if given_nickname in nicknames:
print('{0} is in the nicknames list'.format(given_nickname))
else:
print('{0} is NOT in the list'.format(given_nickname))
如果每次输入昵称时都要编辑文本文件,可以使用以下方法进行编辑。
注意:
当然,如果您在每一行中使用一个干净的文本文件保留每个昵称,则这种情况将起作用:
#Read the file:
file_location = r'somepath'
read_file = open(file_location,'r').read().splitlines()
nicknames = list(read_file) #catch the file as a list, its an optional line for cleaner code
def edit_file(nickname,file_location):
f = open(file_location,'a').write('\n{0}'.format(nickname)) # before adding each nickname,start a new line in the text file
while True:
given_nickname = input('What is your nickname?')
if given_nickname not in nicknames:
print('Welcome {0}!'.format(given_nickname))
edit_file(nickname = given_nickname,file_location = file_location)
break # stop the execution
else:
print('Error! {0} already chosen!'.format(given_nickname))
#looping over the while loop if nickname is taken
在这个问题上,你可以实现很多目标。我相信这两个人中的一个可以完成。你有什么问题?