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

时间:2015-03-26 13:00:58

标签: 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()

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

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

Inserting a string into a list without getting split into characters

How to split a string into a list?

python 3.4.2 joining strings into lists

3 个答案:

答案 0 :(得分:3)

目前的情况是,您将一个字符列表传递给print方法,如果您没有指定分隔符,则每个字符将以打印空格分隔(默认分隔符)。

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

>>> 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

另一种方法是使用print(''.join(phoneNumList))

连接字符并将它们作为单个字符串输入传递给print方法
>>> print(''.join(phoneNumList))
xxx-xxx-xxxx

答案 1 :(得分:2)

尝试这样做:

print(''.join(phoneNumList))

这会将列表连接成不使用分隔符的字符串。

答案 2 :(得分: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 "))
        for position in (6, 3):
            phoneNum = phoneNum[:position] + '-' + phoneNum[position:]
        print(phoneNum)

x = Demographics
x.phoneFunc()

您还可以相当容易地添加改进,例如检查分隔符是否已经存在(即,它是由用户输入的):

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 "))
        phoneNum = phoneNum.replace('-', '') #Get rid of any dashes the user added
        for position in (6, 3):
            phoneNum = phoneNum[:position] + '-' + phoneNum[position:]
        print(phoneNum)

x = Demographics
x.phoneFunc()