设置Python模块的搜索路径有几种方式
- 设置PYTHONPATH环境变量
- 添加.pth文件(先在txt文件中写入需要添加为永久路径的项目路径,然后更改文件后缀名为.pth,再次查看sys.path会发现路径已添加至环境变量)
- 通过sys.path.append()设置路径,这是临时添加,一旦退出python就没有了
- 如果使用PyCharm,可以直接设置搜索路径
PS:【永久设置Python模块搜索路径:PYTHONPATH、.pth文件和PyCharm。临时设置Python模块搜索路径:sys.path、临时设置PYTHONPATH】
字符串与字符串之间连接方式
# 1.加号
s1 = 'hello'
s2 = 'world'
print(s1+s2)
# 2.直接连接
s = 'hello''world'
print(s)
# 3.标准输出的重定向
from io import StringIO
import sys
old_stdout = sys.stdout
s = StringIO()
sys.stdout = s # 让sys.stdout指向s
print('hello','world') #在s中写入hello,world
sys.stdout = old_stdout # 恢复标准输出
s_str = s.getvalue()
print(s_str)
# 4.格式化
s = '%s,%s'%(s1,s2)
print(s)
# 5.join
s = ",".join([s1,s2])
print(s)
字符串与非字符串直接如何连接
# 1.加号
n = 20
s = s1 + str(n)
print(s)
v = 12.44
b = True
print(s1 + str(n) + str(v) + str(b))
# 2.格式化
s = '%s,%d,%.2f,%s' %(s1,n,v,b)
print('格式化:',s)
# 3.重定向
from io import StringIO
import sys
old_stdout = sys.stdout
s = StringIO()
sys.stdout = s
print(s1, b, n,v,sep=',')
sys.stdout =old_stdout # 恢复标准输出
s_str = s.getvalue()
print(s_str)
字符串与对象连接时如何让对象输出特定的内容,如MyClass
class MyClass:
def __str__(self):
# 重写str方法
return 'This is a MyClass Instance.'
my = MyClass()
s = s1 + str(my) #str(my)打印return
print(s)