简体   繁体   中英

How to print a string within a for loop but only once?

I am new to Python and wanted to implement a simple for loop:

phone_number = input("Please print phone number: ")
for i in phone_number:
    if i=="-":
        continue
print(i, end="")

so as you can see, the point of the program is to print the inputted phone number (111-222-3333) without "-" so the output is: 1112223333.

But I want the output to be "Your phone number is: 1112223333." I do not know how to implement the part that reads

print("Your phone number is: ")

I have tried to put this statement within the for loop but because of the end="" put in

print (i, end="")

I get a response that reads like

Your phone number is:
Your phone number is:1
Your phone number is:1
Your phone number is:1,...

I only want the statement to be printed once. What should I do???

Instead of iterating over the characters of the string and printing each character separately, we can remove the '-' by using str.replace(...) :

phone = '111-222-3333'
print(f"Your phone number is: {phone.replace('-','')}")

Using your for loop method, you can do the following to achieve your goal:

phone_number = input("Please print phone number: ")

print("Your phone number is: ", end="")
for i in phone_number:
    if i == "-":
        continue
    print(i, end="")
print()

Note how I've added an indent before the line print(i, end="") so that it is done once per loop, rather than after the for has finished.

I also moved the "your phone number is" part to before the loop, so that it is only printed once before any of the numbers are printed.


If you wanted, you could also invert the if condition to achieve the same result in 1 less line:

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM