user2916405
user2916405

Reputation: 147

how to remove a leading digit if the count of characters are 10 using python

in the code below using rjust(10, '9') I'm adding the number 9 as a leading number to the any string that doesn't have 10 digits.

Now I need to remove the leading number 9 where the strings have 10 digits.

My working code:

dataNew['Telefone Celular'] = '5555-5555'
add9toTell = dataNew['Telefone Celular'].str.rjust(10, '9')
print(add9toTell)
>>> 95555-5555

Now I need to remove the digit 9 if there are 10 digits. I've tried using str.replace() with [1:] but I get nowhere.

Upvotes: 0

Views: 99

Answers (2)

MatBBastos
MatBBastos

Reputation: 401

Just slice when the string has len of 10. This function won't change phone numbers with less than 10 digits (including the dash '-'), and will remove the first digit of the ones with exactly 10 digits.

def remove_first_digit(in_str: str) -> str:
    if len(in_str) == 10:
        return in_str[1:]
    return in_str

Usage:

telefone = "95555-5555"
print(remove_first_digit(telefone))
>>> "5555-5555"

If you're looking for something more general, to deal with the case when you have a dash or a space (or anything that is not a digit), you can use this version of the function:

def remove_first_digit(in_str: str) -> str:
    phone = ''.join([c for c in in_str if c.is_digit()])
    if len(phone) == 9:
        return phone[1:]
    return phone

It just adds a line to make sure you're getting only numbers in the string.

Upvotes: 0

yangcodes
yangcodes

Reputation: 281

arr = [1,2,3,4,5,6,7,8,9,10]
if len(arr) == 10:
    arr = arr[1:]
print(arr)
# prints [2, 3, 4, 5, 6, 7, 8, 9, 10]

You can try something like this by using slice notation and reassignment

Upvotes: 1

Related Questions