Home >Backend Development >Python Tutorial >Correct string encoding specification in python

Correct string encoding specification in python

anonymity
anonymityOriginal
2019-06-17 09:15:586312browse

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.

Correct string encoding specification in python

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 = [&#39;<table>&#39;]
     for last_name, first_name in employee_list:
         items.append(&#39;<tr><td>%s, %s</td></tr>&#39; % (last_name, first_name))
     items.append(&#39;</table>&#39;)
     employee_table = &#39;&#39;.join(items)
No:  employee_table = &#39;<table>&#39;
     for last_name, first_name in employee_list:
         employee_table += &#39;<tr><td>%s, %s</td></tr>&#39; % (last_name, first_name)
     employee_table += &#39;</table>&#39;

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn