python 面试题(2)--- 字符串连接问题

1.字符串与字符串之间连接的方式有5种

代码演示:

#第一种: + (加号)
s1='Hello'
s2='Ailijia'
s=s1 + s2
print("加号连接:",s)

#第二种: 直接连接
s="hello""Ailijia"
print("直接连接:",s)

#第三种: ,(逗号)连接
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print('hello','world')
sys.stdout = old_stdout  #恢复标准输出
result_str = result.getvalue()
print("用逗号连接:",result_str)

#第四种: 格式化连接
s= '%s %s' % (s1,s2)
print("格式化连接:",s)

#第五种: join
s= " ".join([s1,s2])
print("join连接:",s)

运行结果:
在这里插入图片描述

2.字符串与非字符串之间如何连接

代码演示:

#第一种: 加号
n = 20
s=s1 + str(n)
print(s)
m = 12.3
i = True
print(s1 + str(n) + str(m) + str(i))

#第二种: 格式化
s = '%s %d %f' %(s1,n,m)
print("格式化:",s)

#第三种: 重定向
from io import StringIO
import sys
old_stdout = sys.stdout
result = StringIO()
sys.stdout = result
print(s1,True,n,m)
sys.stdout = old_stdout  #恢复标准输出
result_str = result.getvalue()
print("用逗号连接:",result_str)

运行结果:
在这里插入图片描述

3.字符串与对象连接时如何让独享输出特定的内容,如:MyClass

代码演示:

class MyClass:
    def __str__(self):
        return 'This is a MyClass Instance.'
my=MyClass()
s = s1 + str(my)
print(s)

运行结果:
在这里插入图片描述

python 面试题(3)— 进制转换

发布了49 篇原创文章 · 获赞 5 · 访问量 2014

猜你喜欢

转载自blog.csdn.net/qq_44619595/article/details/104139431