Create Python list split on spaces
在python中,如何使用全名并创建另一个名为name_list的变量,该变量将我的名字作为一个列表,在空格上拆分?我知道如何创建name_list=list(全名),但如何在一行中拆分空格?
1 | var full_name ="My Name" |
使用STR.分裂:
string.split(s[,sep[,maxsplit]])
Return a list of the words of the string s. If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). If the second argument sep is present and not None, it specifies a string to be used as the word separator. The returned list will then have one more item than the number of non-overlapping occurrences of the separator in the string. If maxsplit is given, at most maxsplit number of splits occur, and the remainder of the string is returned as the final element of the list (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).
1 | full_name ="My Name".split() |
它将返回一个列表:
1 2 3 4 | In [1]: full_name ="My Name".split() In [2]: full_name Out[2]: ['My', 'Name'] |
要将名字和姓氏分配给变量,可以解包:
1 2 3 4 5 6 7 8 9 | In [3]: full_name ="My Name" In [4]: first, last = full_name.split() In [5]: first Out[5]: 'My' In [6]: last Out[6]: 'Name' |