How do I use Python to easily expand variables to strings?

前端 未结 4 1174
一个人的身影
一个人的身影 2021-02-05 07:52

What\'s a nice idiom to do this:

Instead of: print \"%s is a %s %s that %s\" % (name, adjective, noun, verb)

I want to be able to do something to th

4条回答
  •  不思量自难忘°
    2021-02-05 08:19

    For python 2 do:

    print name,'is a',adjective,noun,'that',verb
    

    For python 3 add parens:

    print(name,'is a',adjective,noun,'that',verb)
    

    If you need to save it to a string, you'll have to concatenate with the + operator and you'll have to insert spaces. print inserts a space at all the , unless there is a trailing comma at the end of the parameters, in which case it forgoes the newline.

    To save to string var:

    result = name+' is a '+adjective+' '+noun+' that '+verb
    

提交回复
热议问题