我是python新手,我想制作一个简单的程序,用詹姆斯·邦德的风格打印出你的名字和介词
因此,如果名称包含任何介词,如“Van”、“Von”、“De”或“Di”,我希望程序将其打印为:
{Preposition} {LastName}, {FirstName} {Preposition} {LastName} *edited
为此,我知道我们需要一个用户名和介词的列表
a = [user input separated with the .split function]
b = [list of prepositions]
为了在名称中找到介词的实例,我发现可以使用下面的代码:
if any(x in a for x in b):
然而,我在打印名字时遇到了一个问题,因为介词可以是前面提到的(列表b)中的任何一个。我无法找到一种打印方法,而不知道它及其在字符串中的位置。首先,我认为可以使用.index函数,但它似乎只能搜索一个单词,而不能根据需要搜索多个单词。我能得到的最接近的结果是:
name_split.index('preposition1') # works
name_split.index('preposition1', 'preposition2', etc.) # does not work
所以我要问的是是否有一种方法可以检查列表(b)中的任何单词是否在输入的文本中使用,并获取所述单词的位置
希望我能解释清楚,希望有人能给我一些帮助。提前多谢各位
我想不出比使用
for
循环更好的方法:产出:
如果要遍历名称列表,可以执行以下操作:
第二类介词(
"Jr.", "Sr."
)的新版本:产出:
使用正则表达式的不同方法(我知道)
为什么名字中的介词很重要?您不会在任何地方打印它,您真正关心的是姓,以及名的其余部分。不需要寻找介词,只需使用^{} 从右边拆分,并要求
maxsplit
为1。例如:然后,您可以简单地打印您认为合适的值
使用
input_name = "Vincent van Gogh"
打印Gogh, Vincent van Gogh
。使用input_name = "James Bond"
,您将得到Bond, James Bond
这样做的另一个好处是,如果人们输入中间名/首字母,它也可以工作
注意,人们写名字的方式有很多奇怪之处,因此值得一看Falsehoods Programmers Believe About Names
相关问题 更多 >
编程相关推荐