Home > Software design >  How to use end="" parameter in f-string print format?
How to use end="" parameter in f-string print format?

Time:04-04

afs="Hello, World! KD herfe"
print("[",end="")
for ad in afs:
    if ad!=" ":
        # print(ad,end="")
        print(f"{ad}")
    else:
        print("",end="")
print("]")

Here I wanted to print afs using f-string in this form

[Hello,World!KDherfe]

Output is right if commented f-string version but I wanted to know how use end parameter in f-string.

enter image description here

CodePudding user response:

afs="Hello, World! KD herfe"
print("[", end="")
for ad in afs:
    if ad != " ":
        print(f"{ad}", end="")

print("]")

You can just use end="" normally after a comma in any print statement. It is a keyword argument (often called a kwarg). It does not matter if your first argument is a string (ie: "["), a variable (ie: ad) or an f-string (ie: f"{ad}").

For what it's worth you can achieve the same thing by calling replace() on an f-string in a single print statement.

afs="Hello, World! KD herfe"
print(f"[{afs}]".replace(" ",""))
  • Related