在Python中将字符串插入列表(v.3.4.2)

CSP*_*FHS 5 python string

我正在学习Python 3.4.2中的函数和类,我从这段代码片段的输出中得到了一些偏见:

print("This program will collect your demographic information and output it")
print ("")

class Demographics:   #This class contains functions to collect demographic info 

    def phoneFunc():  #This function will collect user's PN, including area code
        phoneNum = str(input("Enter your phone number, area code first "))
        phoneNumList = []
        phoneNumList[:0] = phoneNum
        #phoneNumList.insert(0, phoneNum) this is commented out b/c I tried this and it made the next two lines insert the dash incorrectly

        phoneNumList.insert(3, '-')
        phoneNumList.insert(7, '-')
        print(*phoneNumList)

x = Demographics
x.phoneFunc()
Run Code Online (Sandbox Code Playgroud)

当它打印电话号码时,它会将数字空出如下:xxx - xxx - xxxx而不是xxx-xxx-xxxx.

有没有办法删除字符之间的空格?我看过这些线程(第一个是最有帮助的,并且部分地让我上路)但我怀疑我的问题与它们中描述的不完全相同:

将字符串插入列表而不会拆分为字符

如何将字符串拆分为列表?

python 3.4.2将字符串加入列表

mu *_*u 無 3

就目前而言,您正在将一个字符列表传递给 print 方法,如果您不指定分隔符,则每个字符都将以空格分隔(默认分隔符)打印。

如果我们sep在 print 方法调用中指定为空字符串,则字符之间不会有空格。

>>> phoneNumList = []
>>> phoneNumList[:0] = "xxx-xxx-xxxx"
>>> phoneNumList
['x', 'x', 'x', '-', 'x', 'x', 'x', '-', 'x', 'x', 'x', 'x']
>>> print(*phoneNumList)
x x x - x x x - x x x x
>>> print(*phoneNumList, sep="", end="\n")
xxx-xxx-xxxx
Run Code Online (Sandbox Code Playgroud)

另一种方法是连接字符并将它们作为单个字符串输入传递给 print 方法,使用print(''.join(phoneNumList))

>>> print(''.join(phoneNumList))
xxx-xxx-xxxx
Run Code Online (Sandbox Code Playgroud)