Is there a more efficient way of writing this for loop program when handling strings?

Viewed 71

Some Background: Let me clarify on what this is about. I was watching a bro code tutorial on skipping certain characters in a string then printing it in the console without it appearing on a newline. I became familar with the end="" that he used in the print statement.

It lead to another question which was "Hmm, now how do I store that new sequence in a variable?". Eventually, I figured out on how to do the same exact thing without using a print statement nor end="". I used an empty string variable to achieve this but it took awhile to figure out.

Here is the code samples below: Sample A:

original_sequence = "abc-def-ghij"

filtered_sequence = ""
for i in original_sequence:
    if i == "-":
        continue
    filtered_sequence += i

print("Old String:"+original_sequence)
print("Filtered String: "+filtered_sequence)

And here is Bro code's example: Sample B:

phone_number = "123-456-7890"

for i in phone_number:
    if i == "-":
        continue
    print(i,end="")

Now the question that I was intending to ask is: is there a better/more efficient method than Sample A I have given above?

The goal here was to store the output in a variable.

1 Answers

A good and faster way is by using replace() function ,try this instead:

original_sequence = "abc-def-ghij"

filtered_sequence = ""
filtered_sequence=original_sequence.replace("-" ,"")
print("Old String:"+original_sequence)
print("Filtered String: "+filtered_sequence)
Related