美文网首页编程学习
Python字符串引入变量

Python字符串引入变量

作者: myshu | 来源:发表于2020-10-23 14:59 被阅读0次

python字符串引入变量有很多方法

1、使用f-string

这种方法我觉得是最简单和实用的!放在最前面!!
使用方法就是f或F加上双引号或单引号,如f"str{para}"F"str{para}",大括号中的表示替换的变量,如下:

name = "Linda"
str = f"Hello, {name}."
# 'Hello, Linda.'

这里的括号里面也可以是表达式或者函数,比如:

name = "ABC"
str = f"{name.lower()} is funny."
# 'abc is funny.'

如果字符串有括号{},使用两个括号即可

name = "ABC"
str = f"{ABC} is {{}}"
# ABC is {}

单引号和双引号都是使用\来转义即可(注意:大括号外均可使用,但是大括号内不能出现\

name = "ABC"
str = f"{name} is {{}} \"\""
# ABC is {} ""

三引号也是可以用的

name = "ABC"
str = f"""
test {name}
"""
str = f'''
test {name}
'''
# test ABC

录入字典的时候,整个字符串得使用双引号!如果使用单引号会报错,因此,还是习惯使用双引号吧!

name = "ABC"
name = {'name': 'Linda', 'age': 12}
str = f"{name['name']} "  # 注意这里使用的是双引号!!!
# Linda

还可以在大括号里面对变量的格式进行处理

a = 1234567.098765
f'a is {a:f}'
# 'a is 1234567.098765'
f'a is {a:,f}'
# 'a is 1,234,567.098765'
f'a is {a:_f}'
# 'a is 1_234_567_890.098765'
f'a is {a:+f}'
# 'a is +1234567.098765'

2、使用%-formating

使用%s表示变量,然后后面再列出变量

name = "Linda"
age =12
"Hello, %s. Age is %s" % (name, age)
# 'Hello, Linda.'

3、使用str.format()

在字符串中间使用{},后面再加上format指定变量

"Hello, {1}. You are {0}.".format(age, name)  # 可以指定顺序
# 'Hello, Eric. You are 74.'

person = {'name': 'Eric', 'age': 74}
"Hello, {name}. You are {age}.".format(**person)  # 可以处理字典
# 'Hello, Eric. You are 74.'

参考资料:
1.https://realpython.com/python-f-strings/#option-1-formatting
2.https://blog.csdn.net/sunxb10/article/details/81036693

相关文章

网友评论

    本文标题:Python字符串引入变量

    本文链接:https://www.haomeiwen.com/subject/ttyumktx.html