赞
踩
编写函数实现交叉合并字符串,例如:ABCD与1234的合并结果是A1B2C3D4 :
- def mergeStr(str1, str2):
- str3 = ""
- i = 0
- for str in str1:
- if i < len(str2):
- str3 += str + (str2[i])
- i += 1
-
- if i < len(str2):
- for item in range(i, len(str2)):
- str3 += str2[i]
- i += 1
- return str3
-
- else:
- for item in range(i, len(str1)):
- str3 += str1[i]
- i += 1
- return str3
-
-
- if __name__ == '__main__':
- str1 = input("please input first string:\n")
-
- str2 = input("please input second string:\n")
-
-
- print("After the merger:\n"++ str(mergeStr(str1, str2)))

编程思路:
用两个不同的字符串来存储自己要输入的字符串,用一个空白的字符串来把合并后的字符串存储。
定义一个类图书类,图书信息为IBSN、书名、作者、出版社和定价。通过类方法能够显示所有图书信息:
- class Book:
- IBSN = "00001"
- name = "Name"
- author = "Author"
- publisher = "publisher"
- price = "price"
-
- def __init__(self, IBSN, name, author, publisher, price):
- Book.IBSN = IBSN
- Book.name = name
- Book.author = author
- Book.publisher = publisher
- Book.price = price
-
- def to_string(self):
- print("------图书信息为:------\n" +
- "IBSN: " + self.IBSN + "\n"
- + "书名: " + self.name + "\n"
- + "作者: " + self.author + "\n"
- + "出版社: " + self.publisher + "\n"
- + "价格: " + str(self.price))
-
- # 类方法
- @classmethod
- def to_string(self):
- print("------图书信息为:------\n" +
- "IBSN: " + self.IBSN + "\n"
- + "书名: " + self.name + "\n"
- + "作者: " + self.author + "\n"
- + "出版社: " + self.publisher + "\n"
- + "价格: " + str(self.price))
- if __name__ == '__main__':
- Book(input('请输入IBSN号:'), input('请输入书名:'), input('请输入作者:'), input('请输入出版社'), float(input('请输入价格:')))
- Book.to_string()

这位大佬指导:happy488127311的博客_CSDN博客
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。