时间:2021-07-01 10:21:17 帮助过:45人阅读

示例代码如下:
s = 'abcdefghijk' #原字符串 l = list(s) #将字符串转换为列表,列表的每一个元素为一个字符 l[1] = 'z' #修改字符串的第1个字符为z newS = ''.join(l) #将列表重新连接为字符串 print(newS)#azcdefghijk #修改后的字符串
字符串格式化与拼接规范
[强制] 除了a+b这种最简单的情况外,应该使用%或format格式化字符串。
解释
复杂格式化使用%或format更直观
Yes: x = a + b
x = '%s, %s!' % (imperative, expletive)
x = '{}, {}!'.format(imperative, expletive)
x = 'name: %s; score: %d' % (name, n)
x = 'name: {}; score: {}'.format(name, n)
No: x = '%s%s' % (a, b) # use + in this case
x = '{}{}'.format(a, b) # use + in this case
x = imperative + ', ' + expletive + '!'
x = 'name: ' + name + '; score: ' + str(n)·[强制] 不要使用+=拼接字符串列表,应该使用join。
解释
python中字符串是不可修改对象。每次+=会创建一个新的字符串,性能较差。
Yes: items = ['<table>']
for last_name, first_name in employee_list:
items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name))
items.append('</table>')
employee_table = ''.join(items)
No: employee_table = '<table>'
for last_name, first_name in employee_list:
employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name)
employee_table += '</table>'以上就是python中正确的字符串编码规范的详细内容,更多请关注Gxl网其它相关文章!