Reputation: 27
I have a little "problem" that I would like to solve via programming a simple script. I don't have much programming experience and thought I'd ask here for help for what I should look for or know to do this.
Basically I want to take an email address such as [email protected]
and replace it into pl*************[email protected]
.
I need the script to take the letters after the first two, and before the last, and turn those letters into asterisks, and they have to match the amount of characters.
Just for clarification, I am not asking for someone to write this for me, I just need some guidance for how to go about this. I would also like to do this in Python, as I already have Python setup on my PC.
Upvotes: 0
Views: 40
Reputation: 2660
First, let's think about what data type we would store this in. It should be a String since it contains letters and characters.
We know we want to replace a portion of the String from the THIRD character to the character 2 before "@".
Let's think about this in terms of indexing now. The third character, or our start
index for replacement is at index 2. To find the index of the character "@", we can use the: index()
function as so:
end = email.index('@')
However, we want to start replacing from 2 before that index, so we can just subtract 2 from it.
Now we have the indexes (start and endpoint) of what we want to replace. We can now use a substring that goes from the starting to ending indexes and use the .replace()
function to replace this substring in our email
with a bunch of *
's.
To determine how many *
's we need, we can find the difference in indexes and add 1 to get the total number. So we could do something like:
stars = "*" * (end - start + 1)
email = email.replace(email[start:end + 1], stars)
Notice how I did start:end + 1
for the substring. This is because we want to include that ending index, and the substring function on its own will not include the ending index.
I hope this helped answer your question! Please let me know if you need any further clarification or details:)
Upvotes: 1
Reputation: 27577
You can use Python string slicing:
email = "[email protected]"
idx1 = 2
idx2 = email.index("@") - 1
print(email[:idx1] + "*" * (idx2 - idx1) + email[idx2:])
Output:
pl*************[email protected]
Explanation:
email = "[email protected]"
2
:idx = 2
@
symbol is minus 1
:idx2 = email.index("@") - 1
print(email[:idx1] + "*" * (idx2 - idx1) + email[idx2:])
Upvotes: 3
Reputation: 259
So this email will be a string.
Try use a combination of String indexing and (string replacement or string concatenation).
Upvotes: 1