去除字符之间的空格并阻止用户输入包含整数或标点符号

Stripping whitespace in-between characters and stopping user input from containing integers or punctuation

您好,我可以在本文底部的代码中使用一些指针 post。 (顺便说一句,我最近开始学习 Python,因此非常感谢任何反馈,即使它不完全与问题相关)

所以基本上我的代码需要 do/factor 如下:

  1. 根据某人的名字和姓氏打印出他们的用户 ID。
  2. 用户 ID 总共不能超过 8 个字符
  3. 要使用名字的前 2 个字符,然后使用姓氏的后 6 个字符。

一切如我所愿,如名称:

John Doe = "jodoe"
Marie Anne Richardson = "maardson"

但当我们查看以下示例时,一切都变了:

J.K.Rowling = "j.owling"
John D O E = "jod o e "

我不想允许使用标点符号和整数,而且我无法控制字符之间的空格。在某些情况下,名字会类似于 "Marie Anne" 或者人们可能有多个姓氏,因此绝对应该允许用户输入之间的空格,但我正在寻找的是将其删除。

So the user can type "Marie Anne Richardson" and this will still allow user "maardson". However:

"John D O E" would result in "jodoe". "John Doe Doe" would result in "jodoedoe"

代码:

print(
    "Welcome to the UserID Tool, a few questions will be asked to generate your Unique UserID"
)
prompt = ">"
first_name = input(f"What is your First Name?\n{prompt}").lower().strip()
last_name = input(f"What is your Last Name\n{prompt}").lower().strip()

len_first_name = len(first_name)
len_last_name = len(last_name)
max_userid_len = 8

if len_first_name + len_last_name > max_userid_len:
    new_last_name = last_name[-6:].strip()
    print(f"Your user id is {first_name[0:2]}{new_last_name}")
else:
    print(f"Your user id is {first_name[0:2]}{last_name}")

也许使用 .replace() 函数。如果您只关心“.”和“ “你可以利用那几行:

name = input(“Tell the name”)
name1 = name.replace(".", "")
name2 = name1.replace(“ “,””)

我建议您使用 replace() 函数。

你可以这样写: new_first_name = first_name.replace(".", "")

要替换多个子字符串,您应该使用本例中的字典: How to replace multiple substrings of a string?

创建屏幕输入功能通常很有意义,例如:

def get_input(query):
    while True:     #endless loop broken by return of acceptable input
        acceptable = True
        foo = input(query)
        for x in foo:
            if not(x.isalpha() or x.isspace()): #positive selection
                print("No numbers or punctuation allowed")
                acceptable = False
                break
        if len(foo.split()[0]) < 2:    #first word length check
            print("First name must have at least two letters")
            acceptable = False
        if acceptable:   #break up string, erase all whitespace, insert
                         #one whitespace after first name, return
            return foo.split()[0] + ' ' + ''.join(foo.split()[1:])   

然后您可以简单地将问题作为查询调用此函数,用于每个输入。这保证了从函数返回的每个字符串在两个字母字符串之间只有一个空格。

对于干净的正则表达式解决方案 - 我会这样做:

import re

sample_=["John Doe", "J.K.Rowling",  "Marie Anne Richardson", "John D O E", "John Doe Doe"]
res=""
for el in sample_:
    print(f"BEFORE: {el}")
    res=re.sub(r"[^a-z\s]", "", el.lower().strip())
    res=re.sub(r"(?<=\s)([^\s]*)\s", r"", res)
    res=re.sub(r"(^[a-z]{1,2}).{0,}?([a-z]{1,6})$", r"", res)
    print(f"AFTER: {res}")

输出:

BEFORE: John Doe
AFTER: jodoe
BEFORE: J.K.Rowling
AFTER: jkowling
BEFORE: Marie Anne Richardson
AFTER: maardson
BEFORE: John D O E
AFTER: jodoe
BEFORE: John Doe Doe
AFTER: jodoedoe

那里发生了什么:

前 2 re.sub(...) 只是为了摆脱所有非字母字符,除了第一个内部字符串 space (所以你可以肯定地区分名字的第一个词是什么 -获取前 1-2 个字符)。

第二个:"(^[a-z]{1,2}).{0,}?([a-z]{1,6})$"拉:

(1)(第 1 组 - 由于方括号)(^[a-z]{1,2}) 匹配字符串的前两个字母,而它是一个贪心运算符,因此它将匹配所有 2 个字母,如果有 2 个。

(2) 内部:.{0,}? 匹配任意数量的字符,同时是非贪婪的(这就是问号所表示的)——因此它会尽可能少地匹配。

(3)(第 2 组 - 由于方括号)([a-z]{1,6})$ 将匹配最后 6 个字符,而它又是一个贪婪的运算符,因此它将尽可能多地匹配。

整个字符串匹配我们用第 1 组和第 2 组替换(因此我们删除内部部分)。

对 python 正则表达式库的一些引用:re:

https://docs.python.org/3.5/library/re.html