Please repeat String operators

Several of Python's operators work with strings. This section covers the following operators:

• Concatenation (+): Sticks strings together.

• Size testing (<, >): Determines which of two strings is bigger or smaller. Combine and repeat

To concatenate strings, type the first string, the + symbol, and the second string, like so:

>>> hello = "hello" >>> world = "world" >>> hello + world 'helloworld'

Tip If you're working with string literals rather than strings that have names, you don't have to use the + operator to stick them together. You can just put them next to each other on a line, like so:

>>> "It don' mean a thing " "if it ain't got that swing" "It don' mean a thing if it ain't got that swing"

To repeat a string, type the string, the * symbol, and the number of times you want to repeat the string, as shown here:

"It don' mean a thing It don't mean a thing It don' mean a thing"

To concatenate and repeat at the same time, combine the operations, like so:

>>> toasterl = "would you like some toast? " >>> toaster2 = "or how about muffins??? \n" >>> annoying toaster = (toasterl + toaster2)* 3 >>> print annoying toaster would you like some toast? or how about muffins??? would you like some toast? or how about muffins??? would you like some toast? or how about muffins???

The augmented assignment operators += and +* also work with strings. These operators let you perform an operation and give the result to a name at the same time. They are very useful in loops because they make the assignment statement easy to read.

REMEMBER The + and * operators work differently on strings than they do on numbers.

You can't add a string and a number together—you must first convert the string to a number (for example, by using the int() or float() functions). And if you try to use * on a string and an integer, you get a repeated string, not multiplication, like this:

Was this article helpful?

0 0

Post a comment