Python错题集-问题2:invalid escape sequence(无效的转义序列)

1问题描述:

今日在学习绘制多组直方图过程中,遇到"SyntaxWarning: invalid escape sequence"

SyntaxWarning: invalid escape sequence '\s'
  label=r'$\mu = $ ' + str(mu1) + ', $\sigma = $ ' + str(sigma1))

绘图仍然能够显示,但是程序报错。

2代码详情:

#导入相关库
import numpy as np   #导入numpy库
import matplotlib.pyplot as plt    #导入matplotlib的绘图模块

#准备相关数据
N = 1000

mu1 = 5
mu2 = 10
mu3 = 15

sigma1 = 5
sigma2 = 3
sigma3 = 2

x1 = np.random.randn(N) * sigma1 + mu1
x2 = np.random.randn(N) * sigma2 + mu2
x3 = np.random.randn(N) * sigma3 + mu3

plt.figure(dpi=120)
# 使用matplotlib的hist函数绘制x的直方图
plt.hist(
x1, #变量1
bins=30,
color='royalblue',
label=r'$\mu = $ ' + str(mu1) + ', $\sigma = $ ' + str(sigma1))
plt.hist(
x2, #变量2
bins=30,
color='tomato',
label=r'$\mu = $ ' + str(mu2) + ',$\sigma = $ ' + str(sigma2))
plt.hist(
x3, #变量3
bins=30,
color='gray',
label=r'$\mu = $ ' + str(mu3) + ', $\sigma = $ ' + str(sigma3))


#显示图例
plt.legend()

#显示图表
plt.show()

3问题拆解:

"SyntaxWarning: invalid escape sequence" 是Python语法警告的一种类型,它表示在字符串中使用了无效的转义序列(escape sequence)。

4知识点回顾:

在Python中,转义序列以反斜杠(\)开头,并用于表示特殊字符,例如换行符(\n)、制表符(\t)等。但有时候,如果反斜杠后面跟着的字符不是有效的转义序列,则会收到此警告。

例如,在我的代码中,字符串 r'$\mu = $ ' 中的双反斜杠(\)被视为转义序列的开始,然而在这种情况下,它并不是有效的转义序列。因此,出现了 "SyntaxWarning: invalid escape sequence" 警告。

5解决方案:

对于转义反斜杠字符:在反斜杠之前再添加一个额外的反斜杠来转义反斜杠本身。

label=r'$\mu = $ ' + str(mu1) + ', $\\sigma = $ ' + str(sigma1)

6代码修改 

#导入相关库
import numpy as np   #导入numpy库
import matplotlib.pyplot as plt    #导入matplotlib的绘图模块

#准备相关数据
N = 1000

mu1 = 5
mu2 = 10
mu3 = 15

sigma1 = 5
sigma2 = 3
sigma3 = 2

x1 = np.random.randn(N) * sigma1 + mu1
x2 = np.random.randn(N) * sigma2 + mu2
x3 = np.random.randn(N) * sigma3 + mu3

plt.figure(dpi=120)
# 使用matplotlib的hist函数绘制x的直方图
plt.hist(
x1, #变量1
bins=30,
color='royalblue',
label=r'$\mu = $ ' + str(mu1) + ', $\\sigma = $ ' + str(sigma1))
plt.hist(
x2, #变量2
bins=30,
color='tomato',
label=r'$\mu = $ ' + str(mu2) + ',$\\sigma = $ ' + str(sigma2))
plt.hist(
x3, #变量3
bins=30,
color='gray',
label=r'$\mu = $ ' + str(mu3) + ', $\\sigma = $ ' + str(sigma3))


#显示图例
plt.legend()

#显示图表
plt.show()


Python单词学习

  1. SyntaxWarning:语法警告
  2. invalid:无效的
  3. escape sequence:转义序列

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Pythoner研习社

整理不易,感谢金主!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值