Python面试题:字符串连接

时间:2022-07-28
本文章向大家介绍Python面试题:字符串连接,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

面试题中Python字符串考点

字符串与字符串之间连接有几种方式

答:5种

  1. +号(加号)
  2. 直接连接
  3. 格式化
  4. 用逗号(,)连接,标准输出的重定向
  5. join方法
s = "hello""world"
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)

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

  1. +号
  2. 格式化
  3. 重定向

字符串与对象连接时如何让对象输出特定的内容,如Myclass

class Myclass:
    def __str__(self):
        return 'This is a Myclass Instance.'

my = Myclass()
s = s1 + str(my)
print(s)