这些单引号在第2行的开头起什么作用?

2024-05-08 18:11:49 发布

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

我在某个随机网站上发现了以下解释串联的代码:

data_numb = input("Input Data, then press enter: ")
numb = ''.join(list(filter(str.isdigit, data_numb)))
print('(' + numb[:3] + ') ' + numb[3:6] + '-' + numb[6:])

我想知道单引号在

numb = ''.join(

感谢您的帮助!你知道吗


Tags: 代码inputdata网站filterlistpressenter
1条回答
网友
1楼 · 发布于 2024-05-08 18:11:49

^{}是来自str类的方法。你知道吗

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

''.join(("Hello", "World"))将返回'HelloWorld'。你知道吗

';'.join(("Hello", "World", "how", "are", "you"))将返回'Hello;World;how;are;you'。你知道吗

如果需要在字符串列表(或任何iterable)中的每个元素之间添加分隔符,join非常有用。你知道吗

看起来没什么,但如果不使用join,由于边缘效应,这种操作通常难以实现:

对于字符串列表或元组:

def join(list_strings, delimiter):
    str_result = ''
    for e in list_strings[:-1]:
        str_result += e + delimiter

    if list_strings:
        str_result += list_strings[-1]

    return str_result

对于任何iterable:

def join(iterable, delimiter):
    iterator = iter(iterable)
    str_result = ''
    try: 
        str_result += next(iterator)
        while True:
            str_result += delimiter + next(iterator)
    except StopIteration:
        return str_result

因为join适用于任何iterable,所以不需要从筛选结果创建列表。你知道吗

numb = ''.join(filter(str.isdigit, data_numb))

同样有效

相关问题 更多 >