我想做些
print("hello, your name is [name]")
但我不想这样做
print("hello, your name is "+name)
因为我希望能够将[name]
放在字符串中的任何位置。
在python中有什么方法吗?
答案 0 :(得分:3)
选项1,旧样式格式。
>>> name = 'Jake'
>>> print('hello %s, have a great time!' % name)
hello Jake, have a great time!
选项2,使用str.format
。
>>> print('hello {}, have a great time!'.format(name))
hello Jake, have a great time!
选项3,字符串连接。
>>> print('hello ' + name + ', have a great time!')
hello Jake, have a great time!
选项4,格式字符串(自Python 3.6起)。
>>> print(f'hello {name}, have a great time!')
hello Jake, have a great time!
选项2和4是preferred。要全面了解Python字符串格式,请查看pyformat.info。
答案 1 :(得分:1)
print(f"hello, your name is {name}")
它称为f字符串:https://docs.python.org/3/reference/lexical_analysis.html#f-strings
还有其他方法。
答案 2 :(得分:0)
这称为字符串格式:print('Hello, my name is {}'.format(name))
您还可以做一些更复杂的事情:
print('Hello, my name is {0}, and here is my name again {0}'.format(name)'
答案 3 :(得分:0)
在python3.6中,您可以使用f字符串:
print(f'your name is {name}')
或者您可以使用格式:
print('your name is {}'.format(name))
答案 4 :(得分:0)
print("hello, your name is %s" % ('name'))
也对您有用。
您可以将其扩展到更多变量,例如:
>>> print("%s, your name is %s" % ('hello', 'name'))
hello, your name is name