繁体   English   中英

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

[英]Inserting strings into lists in Python (v. 3.4.2)

我正在学习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()

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

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

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

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

python 3.4.2将字符串加入列表

就像目前的情况一样,您将一个字符列表传递给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方法,使用print(''.join(phoneNumList))

>>> print(''.join(phoneNumList))
xxx-xxx-xxxx

试着这样做:

print(''.join(phoneNumList))

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

为什么要首先制作清单呢? 只需更改字符串:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM