String
The string is one of the basic data types in Python. It is simply some characters inside quotes. The characters can be letters, numbers, punctuation, or any other symbol that you can type.
You can define strings using:
- Single quotes
- Double quotes
- Triple quotes (for multi-line strings)
String examples:
"Hello!" # a string in double quotes
'1234' # a string in single quotes
'''This is a multi-line string!
this is the second line,
this is the third line.
'''
Note: triple quotes also have another usage. They are often used as multi-line comments to disable some lines of code. See an example:
# triple quotes work as multi-line comments
print(1)
'''
print(2)
print(3)
'''
print(4)
The console result:
1
4
The middle two lines are commented out by the triple quotes, and are not run by the computer.
String Operations
String Concatenation: +
In Python, strings can be 'added' together using the addition operator, like this:
str1 + str2
The +
operator represents concatenation. Adding two strings together concatenates them, or links them together. 'Hello ' + 'world!'
returns 'Hello world!'
Example:
If you add two number strings, the result is not the mathematical sum of the two numbers.
s1 = '2'
s2 = '6'
s3 = s1 + s2
print(s3) # 26
print(type(s3)) # <class 'str'> (a string, not a number)
String Multiplication: *
"Multiplying" a number and a string returns the string repeated that many times. For example, 'la' * 3
returns 'lalala'
.
One of the operands has to be a string and the other has to be an integer.
A number string multiplied by 2 won't return 2 times the number:
s = '3'
print(2 * s) # 33 (not 2 * 3 = 6)
print(type(2 * s)) # <class 'str'>