I'm currently carrying out work on the formatting of Ireland Phone Numbers. There's a number of different characters that need to be removed from the beginning. This is a small sample of the code. I'm wondering if there is another method to carry this out like a dictionary so that it is [353:3, 00353:5, 0353:4...] and it slices the beginning based on the length of the matched string? Thanks in advance.
if s.startswith("353") == True:
s = s[3:]
if s.startswith("00353") == True:
s = s[5:]
if s.startswith("0353") == True:
s = s[4:]
if s.startswith("00") == True:
s = s[2:]
You could do something like this and replace the start with an empty string if found.
s = "00353541635351651651"
def remove_prefix(string):
starters = ["353", "00353", "0353", "00"]
for start in starters:
if string.startswith(start):
return string.replace(start, "")
print(remove_prefix(s))
If these are mutually exclusive, you can use a regular expression to check for them all at once. You can also combine similar patterns, eg 353
, 0353
, 00353
can be combined by matching a number of 0
followed by 353
.
import re
s = re.sub(r'^(0{0,2}353|00)', '', s)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.