In Python, strings are immutable objects (immutable), so a certain character of the string cannot be directly modified. One possible way is to convert the string into a list, modify the elements of the list, and then reconnect it into a string.
The sample code is as follows:
s = 'abcdefghijk' #原字符串 l = list(s) #将字符串转换为列表,列表的每一个元素为一个字符 l[1] = 'z' #修改字符串的第1个字符为z newS = ''.join(l) #将列表重新连接为字符串 print(newS)#azcdefghijk #修改后的字符串
String formatting and splicing specifications
[Mandatory ] Except for the simplest case of a b, you should use % or format to format the string.
Explanation
Complex formatting is more intuitive using % or 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)
·[Mandatory] Do not use = splicing characters For string lists, join should be used.
Explanation
Strings in python are unmodifiable objects. Each time = will create a new string, which has poor performance.
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>'
The above is the detailed content of Correct string encoding specification in python. For more information, please follow other related articles on the PHP Chinese website!