Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to mask a number with stars except the last 4 digits in Python

2 Answers

0 votes
def mask_number(val: str | int, mask_char: str = "*", visible_count: int = 4) -> str:
    s = str(val)
    if len(s) <= visible_count:
        return s  # Too short to mask
    
    return mask_char * (len(s) - visible_count) + s[-visible_count:]

# Example Usage
card_number = "1234567890123456"
print(mask_number(card_number))  # Output: ************3456
print(mask_number(9876543210))    # Output: ******3210



'''
run:

************3456
******3210

'''

 



answered 8 hours ago by avibootz
0 votes
def mask_digits_only(val: str, visible_count: int = 4) -> str:
    # Find positions of all digits
    digit_indices = [i for i, char in enumerate(val) if char.isdigit()]
    
    # Identify which digit positions to mask (all except the last `visible_count`)
    to_mask = set(digit_indices[:-visible_count])
    
    return "".join("*" if i in to_mask else char for i, char in enumerate(val))

# Example Usage
formatted_card = "1234-5678-9012-3456"
print(mask_digits_only(formatted_card))  # Output: ****-****-****-3456


'''
run:

****-****-****-3456

'''

 



answered 8 hours ago by avibootz
...