Visitar URL original
String Operators – Real Python
The Wayback Machine - https://web.archive.org/web/20191213235430/https://realpython.com/lessons/string-operators/

String Operators

You may have already seen operators applied to numeric operands. In this lesson, you’ll see how operators can be applied to strings as well. Here are the operators you’ll practice using in this lesson:

  • The + operator concatenates strings:
>>>
>>> s = 'spam'
>>> t = 'egg'
>>> u = 'bacon'

>>> s + t
'spamegg'
>>> s + t + u
'spameggbacon'
  • The * operator creates multiple copies of a string:
>>>
>>> s = 'spam'
>>> n = 2

>>> s * n
'spamspam'

>>> s = 'spam.'
>>> n = 8
>>> s * n
'spam.spam.spam.spam.spam.spam.spam.spam.'
  • The in and not in operators provide boolean testing of membership within a string:
>>>
>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s in 'I saw The Holy Grail!'
False

>>> s not in 'I saw The Holy Grail!'
True
>>> s not in 'I saw spamalot!'
False

To learn more, check out Operators and Expressions in Python. Here are a few resources on using the REPL (Read Eval Print Loop):

Comments & Discussion

Become a Member to join the conversation.