简体   繁体   中英

How do I get my code to print with single quotes?

email = email.split('@', 1)[0]
fname = email.split('.', 1)[0]
lname = email.split('.', 1)[1]
name =("\'"+lname.upper()+","+fname.upper()+"\'")
print(name)

This is my code, email is given as a string with the format firstname.lastname@example.com Now everything works fine except when it outputs it will output in the form LASTNAME,FIRSTNAME but I need it to print with single quotes like 'LASTNAME,FIRSTNAME'. As you can see I have made use of \' to do this but I was wondering if theres a more efficient way to do this. thanks

You don't need the slash before the single quotes. Simply use the single quotes inside the double quotes like so: print("'" + lname.upper() + "," + fname.upper() + "'")

One alternative is to use template string literals as follows:

print(f"'{lname.upper()},{fname.upper()}'")

Template literals allow you to intermix values into your string. More examples uses of them to give an idea:

x = 2
y = 3
print(f'{x} + {y} = {x + y}') # prints 2 + 3 = 5

Both the way you are doing it, and the one described above is perfectly valid.

Try this

name = "'{},{}'".format(lname.upper(),fname.upper())

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