Inserting strings into lists in Python (v. 3.4.2)

I learn about functions and classes in Python 3.4.2, and I digress a bit from the output of this piece of code:

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

When he prints a phone number, he displays the numbers as follows: xxx - xxx - xxxx, not xxx-xxx-xxxx.

Is there a way to remove spaces between characters? I looked at these threads (the first one was the most useful, and I partially depended on it), but I suspect that my problem is not quite the same as what is described in them:

Insert a string into a list without character separation

How to split a string into a list?

python 3.4.2 combining strings into lists

+4
source share
3 answers

, , , ( ), .

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(''.join(phoneNumList))
xxx-xxx-xxxx
+3

:

print(''.join(phoneNumList))

, .

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

All Articles