I am learning about Functions and Classes in Python 3.4.2, and I got a little sidetracked by the output from this code snippet:
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()
When it prints the phone number, it spaces the digits out like this: x x x - x x x - x x x x rather than xxx-xxx-xxxx.
Is there a way to remove the spaces between the characters? I've looked at these threads (the first one was the most helpful, and got me partly on my way) but I suspect my problem isn't exactly the same as what's described in them:
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
To do this we use the split() method in string. The split method is used to split the strings and store them in the list. The built-in method returns a list of the words in the string, using the “delimiter” as the delimiter string.
The split() method is the recommended and most common method used to convert string to list in Python.
Use the str. split() method to split the string into a list of strings. Use the map() function to convert each string into an integer. Use the list() class to convert the map object to a list.
Using the * symbol to print a list in Python. To print the contents of a list in a single line with space, * or splat operator is one way to go. It passes all of the contents of a list to a function. We can print all elements in new lines or separated by space and to do that, we use sep=”\n” or sep=”, ” respectively.
As it currently stands, you are passing a list of characters to the print method, each of which will be printed space separated (default separator) if you do not specify a separator.
If we specify the sep
as empty string in the print method call, there will be no spaces in between the characters.
>>> 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
The other approach is to join the characters and pass them as a single string input to the print method, using print(''.join(phoneNumList))
>>> print(''.join(phoneNumList))
xxx-xxx-xxxx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With