Several methods Python string splicing

A plus sign

First, by the + sign in the form of:

>>> a, b = 'hello', ' world'
>>> a + b
'hello world'

Comma connection

The second, by, in the form of a comma:

>>> a, b = 'hello', ' world'
>>> print(a, b)
hello  world

However, use a comma to note that printing is used only for print, the assignment will generate tuples:

>>> a, b
('hello', ' world')

direct connection

Third, whether the space can be connected directly to the middle:

print('hello'        ' world')
print('hello''world')

%

Fourth, use the% operator.

In previous Python 2.6,% operators is the only way of formatting a string, it can also be used to connect strings.

print('%s %s' % ('hello', 'world'))

format

Fifth, use the format method.

format string formatting method is an alternative to the operator of the Python 2.6% occurred, and can also be connected string.

print('{}{}'.format('hello', ' world')

join

Sixth, use the built-join method.

String has a built-in methods join, which is a sequence of parameter types, such as array tuple or the like.

print('-'.join(['aa', 'bb', 'cc']))

f-string

Seventh, using the f-string mode.

Python 3.6 introduced Formatted String Literals (literal string format), referred to as f-string, f-string evolution operator and format version% methods, use of f-string connection string and use the% operator , similar to the format method.

>>> aa, bb = 'hello', 'world'
>>> f'{aa} {bb}'
'hello world'

*

Eighth, the use of the * operator.

>>> aa = 'hello '
>>> aa * 3
'hello hello hello '

summary

When connecting a small string

We recommend using the + operator.

If you have high requirements for performance, and python version 3.6 or more is recommended f-string. For example, a case where f-string is much better than the readability + Number:

a = f 'Name: {name} Age: {age} Gender: Gender {}'
B = 'Name:' + name + 'Age:' + age + 'gender:' + Gender
# organize a small series data Python and PDF, need to learn Python learning materials can be added to the group: 631 441 315, anyway idle is idle it, it is better to learn a lot friends ~ ~

When connecting a large number of strings

Recommended join and f-string mode, still depends on Python version you are using and the requirements for the selection of readability.

Guess you like

Origin www.linuxidc.com/Linux/2019-08/160090.htm