2

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.

Zecky333
  • 21
  • 1
  • Does this answer your question? [Python string class like StringBuilder in C#?](https://stackoverflow.com/questions/2414667/python-string-class-like-stringbuilder-in-c) – Luatic Jun 01 '22 at 18:56
  • 4
    `filtered_sequence = ''.join(original_sequence.split('-'))` – sahasrara62 Jun 01 '22 at 18:58
  • 3
    `filtered_sequence = original_sequence.replace('-', '')`? – j1-lee Jun 01 '22 at 19:01
  • 1
    @sahasrara62 That is a Python reference. It's asking how to do something in Python based on a similar C# feature. – Barmar Jun 01 '22 at 19:29
  • lots of ways to do it :D `filtered = ''.join(c for c in original if c not in '-')` – Kurt Jun 01 '22 at 22:58

1 Answers1

-1

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)