在Python中重新格式化简单的字符串/列表

2024-06-01 10:08:09 发布

您现在位置:Python中文网/ 问答频道 /正文

重新格式化字符串,例如转换作者列表,如

"David Joyner, Ashok Goel, Nic Papin"

"Joyner, D., Goel, A., Papin, N."

不知道该怎么解决这个问题。我知道它很简单,只使用了.split().strip()等方法,但我不知道需要什么组合。在我变成多比之前,请帮帮我。你知道吗


Tags: 方法字符串列表作者splitdavidstripnic
3条回答

这应该管用。你知道吗

s = "David Joyner, Ashok Goel, Nic Papin"
s_list = s.split()
s_result = ""
for i,name in enumerate(s_list):
    # Even number elements are first names and should be turned into single letters.
    if i % 2 == 0:
        inital = name[0]
    else:
        # Since we only split on spaces, in the odd case, name has a comma already appended.
        s_result += name + " " + inital + "., "
# [:-2] removes both the trailing space and the comma. 
print(s_result[:-2])

# Joyner, D., Goel, A., Papin N.

稍微简单一点的版本是:

s = "David Joyner, Ashok Goel, Nic Papin"
names = s.split(",")
result = ""
for name in names:
    first, last = name.split()
    result += last + ', ' + first[0] + '., '
print(result[:-2])

但是涉及到一个额外的split操作,如果您有大量的名称(否则这将是一个可以忽略不计的更改),那么它将变得更慢。你知道吗

使用姓氏做一些特定的事情:

因此,如果要对列表的最后一个元素执行特定操作,可以通过两种方式执行:

最具python风格的是像第一个示例中那样使用enumerate,并捕获index == len(list) - 1(最后一个元素)的情况:

s = "David Joyner, Ashok Goel, Nic Papin"
names = s.split(",")
result = ""
for index, name in enumerate(names):
    first, last = name.split()
    # Checks if index is lower than last.
    if index < (len(names) - 1):
        result += last + ', ' + first[0] + '., '
    else: 
        result += '& ' + last + ", " + first[0] + '.'
print(result)

但是,如果您坚决反对使用enumerate,那么您可以通过只遍历列表中倒数第二个元素并在循环外执行最后一个操作来获得相同的行为:

s = "David Joyner, Ashok Goel, Nic Papin"
names = s.split(",")
result = ""
for name in names[:-1]:
    first, last = name.split()
    result += last + ', ' + first[0] + '., '
# Final element operation.
first, last = names[-1].split()
result += '& ' + last + ", " + first[0] + '.'
print(result)

实际上,您应该只使用enumerate,这是它的预期用例。不管您选择哪种算法,您都会注意到我们打印的是result,而不是result[:-2]。这是因为我们不再像以前那样在姓氏中添加不必要的字符。你知道吗

查看list comprehensionsstr.joinstr.format。如果您经常使用python,您会发现它们都非常有用。你知道吗

s = "David Joyner, Ashok Goel, Nic Papin"
fl_names = [name.split() for name in s.split(",")]
formatted_names = ["{0}, {1}.".format(last, first[0]) for first, last in fl_names]
result = ", ".join(formatted_names)

你也可以用嵌套的列表理解把所有的东西塞进一起,但是你可以看到这会变得很难快速阅读。你知道吗

", ".join(["{0}, {1}.".format(last, first[0]) 
        for first, last in [name.split() for name in s.split(",")]])

相关问题 更多 >