How to return a set of elements as a single string?

Asked

Viewed 26 times

-1

I found this exercise in Code Wars where they expect to receive a single string, which will be a phone number, with the following format:

"(294) 926-8617"

But the best I can do is without the quotation marks:

(294) 926-8617

This is my code:

import random as rd

def create_phone_number(n):
    b = ""
    for number in range(len(n)):
        a = rd.choice(n)
        b += str(a)
        if len(b) == 10:
            print('(', end='')
            print(''.join(map(str, b[:3])), end='')
            print(')', end=' ')
            print(''.join(map(str, b[3:6])), end='-')
            print(''.join(map(str, b[6:])))


n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

create_phone_number(n)

2 answers

0

It’s not just adding two prints with one quote in each?

Thus:

#aspa no começo
print('"', end='')

print('(', end='')
print(''.join(map(str, b[:3])), end='')
print(')', end=' ')
print(''.join(map(str, b[3:6])), end='-')
print(''.join(map(str, b[6:])), end='')

#aspa no final
print('"')

Or you could concatenate all variables and values like this:

phone = '"('
phone += ''.join(map(str, b[:3]))
phone += ') ' + ''.join(map(str, b[3:6])) + '-'
phone += ''.join(map(str, b[6:])) + '"'
print(phone)

0

If your problem is not knowing how to add the quotes, just put them at the beginning of the first impression and on end of the second impression, thus:

if len(b) == 10:
    print('"(', end = '')
    # Outros prints ...
    print(''.join(map(str, b[6:])), end = '"')

Another thing also that you can do, is to make your code much smaller and much simpler. Just use the method format() to define how your string will look and then pass the values as parameter.

In addition, your role should create a phone number and not print a number. You could then return the string with the phone number created. See below:

def create_phone_number(n):

    numbers = [rd.choice(n) for i in range(10)]
    return '"({}{}{}) {}{}{}-{}{}{}{}"'.format(*numbers)

n = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

phone_number = create_phone_number(n)
print(phone_number)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.