In Python, can you have variables within triple quotes? If so, how?

后端 未结 7 1521
栀梦
栀梦 2020-12-14 05:33

This is probably a very simple question for some, but it has me stumped. Can you use variables within python\'s triple-quotes?

In the following example, how do use

相关标签:
7条回答
  • 2020-12-14 05:48

    The preferred way of doing this is using str.format() rather than the method using %:

    This method of string formatting is the new standard in Python 3.0, and should be preferred to the % formatting described in String Formatting Operations in new code.

    Example:

    wash_clothes = 'tuesdays'
    clean_dishes = 'never'
    
    mystring =""" I like to wash clothes on {0}
    I like to clean dishes {1}
    """
    
    print mystring.format(wash_clothes, clean_dishes)
    
    0 讨论(0)
  • 2020-12-14 05:52

    One of the ways in Python 2 :

    >>> mystring =""" I like to wash clothes on %s
    ... I like to clean dishes %s
    ... """
    >>> wash_clothes = 'tuesdays'
    >>> clean_dishes = 'never'
    >>> 
    >>> print mystring % (wash_clothes, clean_dishes)
     I like to wash clothes on tuesdays
    I like to clean dishes never
    

    Also look at string formatting

    • http://docs.python.org/library/string.html#string-formatting
    0 讨论(0)
  • 2020-12-14 05:55

    Yes! Starting from Python 3.6 you can use the f strings for this: They're interpolated in place, so mystring would have the desired value after the mystring = ... line:

    wash_clothes = 'tuesdays'
    clean_dishes = 'never'
    
    mystring = f"""I like to wash clothes on {wash_clothes}
    I like to clean dishes {clean_dishes}
    """
    
    print(mystring)
    

    Should you need to add a literal { or } in the string, you would just double it:

    if use_squiggly:
        kind = 'squiggly'
    else:
        kind = 'curly'
    
    print(f"""The {kind} brackets are:
      - '{{', or the left {kind} bracket
      - '}}', or the right {kind} bracket
    """)
    

    would print, depending on the value of use_squiggly, either

    The squiggly brackets are:
      - '{', or the left squiggly bracket
      - '}', or the right squiggly bracket
    

    or

    The curly brackets are:
      - '{', or the left curly bracket
      - '}', or the right curly bracket
    
    0 讨论(0)
  • 2020-12-14 05:55

    Also note that you don't need the intermediate variable:

    name = "Alain"
    print """
    Hello %s
    """ % (name)
    
    0 讨论(0)
  • 2020-12-14 06:08

    Pass multiple args in simple way

    wash_clothes = 'tuesdays'
    clean_dishes = 'never'
    a=""" I like to wash clothes on %s I like to clean dishes %s"""%(wash_clothes,clean_dishes)
    print(a)
    
    0 讨论(0)
  • 2020-12-14 06:09

    Yes. I believe this will work.

    do_stuff = "Tuesday"

    mystring = """I like to do stuff on %(tue)s""" % {'tue': do_stuff}

    EDIT: forgot an 's' in the format specifier.

    0 讨论(0)
提交回复
热议问题