how to use concatenate a fixed string and a variable in Python

前端 未结 6 1538
借酒劲吻你
借酒劲吻你 2020-12-05 23:16

I want to include file name \'main.txt\' in the subject for that I am passing file name from command line. but getting error in doing so

python sample.py ma         


        
相关标签:
6条回答
  • 2020-12-05 23:22
    variable=" Hello..."  
    print (variable)  
    print("This is the Test File "+variable)  
    

    for integer type ...

    variable="  10"  
    print (variable)  
    print("This is the Test File "+str(variable))  
    
    0 讨论(0)
  • 2020-12-05 23:24

    I'm guessing that you meant to do this:

    msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
    # To concatenate strings in python, use       ^ 
    
    0 讨论(0)
  • 2020-12-05 23:34

    If you need to add two strings you have to use the '+' operator

    hence

    msg['Subject'] = your string + sys.argv[1]
    

    and also you have to import sys in the begining

    as

    import sys
    
    msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
    
    0 讨论(0)
  • 2020-12-05 23:43

    I know this is a little old but I wanted to add an updated answer with f-strings which were introduced in Python version 3.6:

    msg['Subject'] = f'Auto Hella Restart Report {sys.argv[1]}'
    
    0 讨论(0)
  • 2020-12-05 23:46

    With python 3.6+:

    msg['Subject'] = f"Auto Hella Restart Report {sys.argv[1]}"

    0 讨论(0)
  • 2020-12-05 23:48

    Try:

    msg['Subject'] = "Auto Hella Restart Report " + sys.argv[1]
    

    The + operator is overridden in python to concatenate strings.

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