- 软件自动化测试实战解析:基于Python3编程语言
- 徐西宁编著
- 516字
- 2021-07-23 16:17:33
2.7.1 拼接和格式化
字符串最常见的操作之一就是拼接。对于简单的拼接,我们可以用“+”操作符很容易地做到。
>>> name = 'world' >>> greeting = 'Hello ' + name >>> print(greeting) Hello world
复杂一些的情况,我们还是可以通过“+”操作符来进行。
>>> pick_2002 = 'Yao Ming' >>> pick_2003 = 'LeBron James' >>> nba_draft_picks = 'First draft pick of NBA 2002 is ' + pick_2002 + ', and the first draft pick of NBA 2003 is ' + pick_2003 >>> print(nba_draft_picks) First draft pick of NBA 2002 is Yao Ming, and the first draft pick of NBA 2003 is LeBron James
更复杂一些的情况,我们仍然可以通过“+”操作符来完成,但是,这需要做大量碎片化的细节处理,很容易出错,也不容易看出拼接字符串的最终全貌,这会带来编码、阅读和维护方面的困难,我们需要更合适的方式来完成这类任务。
针对这种情况,我们可以用字符串的format方法。
>>> pick_2002 = 'Yao Ming' >>> pick_2003 = 'LeBron James' >>> 'First draft pick of 2002 is {}, and the first draft pick of 2003 is {}'. format(pick_2002, pick_2003) 'First draft pick of 2002 is Yao Ming, and the first draft pick of 2003 is LeBron James'
可以给括号占位符加上序号,进一步减少出错的可能。
>>> pick_2002 = 'Yao Ming' >>> pick_2003 = 'LeBron James' >>> 'First draft pick of 2002 is {0}, and the first draft pick of 2003 is {1}'. format(pick_2002, pick_2003) 'First draft pick of 2002 is Yao Ming, and the first draft pick of 2003 is LeBron James'
甚至可以给占位符加上名字,这样,可读性和可维护性会进一步提高。
>>> pick_2002 = 'Yao Ming' >>> pick_2003 = 'LeBron James' >>> 'First draft pick of 2002 is {pick_2002_name}, and the first draft pick of 2003 is {pick_2003_name}'.format(pick_2002_name=pick_2002, pick_2003_ name=pick_2003) 'First draft pick of 2002 is Yao Ming, and the first draft pick of 2003 is LeBron James'
通过占位符,format方法可以很灵活地处理字符串的格式化,同时还可以使代码具有很高的可读性和可维护性。