简体   繁体   English

如何在for循环中打印一个字符串但只打印一次?

[英]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:我是 Python 的新手,想实现一个简单的 for 循环:

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.如您所见,程序的重点是打印输入的电话号码(111-222-3333),不带“-”,因此 output 为:1112223333。

But I want the output to be "Your phone number is: 1112223333."但我希望 output 是“您的电话号码是: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我试图将此语句放在 for 循环中,但由于end=""放入

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(...) :我们可以使用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:使用您的 for 循环方法,您可以执行以下操作来实现您的目标:

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.请注意我是如何在print(i, end="")行之前添加缩进的,以便每个循环执行一次,而不是在for完成之后。

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:如果您愿意,您还可以反转if条件以在少 1 行中实现相同的结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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