Working with Strings in Python
Working with Strings in Python
In Python you can create strings with either single quotes or double quotes.
'hello' # single-quoted string
"hello" # double-quoted stringFrom Python's point of view these are the same string. We can check that with the == operator:
'hello' == "hello" # TrueSingle and Double Quotes
Different quote styles are useful when you want to nest quotes inside a string. For example:
'I said: "hello"'Or the other way around, with single quotes inside double quotes:
"I said: 'hello'"These two strings are different because a single quote character and a double quote character are not the same thing.
"I said: 'hello'" == 'I said: "hello"' # FalseEscaping Quotes
If you need double quotes inside a string that is itself wrapped in double quotes, you need to escape them with a backslash \:
"I said: \"hello\""Without escaping, Python raises a syntax error because it can no longer tell where the string starts and ends.
String Concatenation
You can add strings together. This is called concatenation. The result is a new string made from both parts.
'Hello' + ' Vadya' # 'Hello Vadya'You can also place string literals next to each other without a plus sign. Python joins them automatically:
'Hello' " Vadya" # 'Hello Vadya'String Repetition
You can multiply a string by an integer. Python repeats the string that many times:
"Hello " * 3 # 'Hello Hello Hello 'If you multiply by zero or a negative integer, the result is an empty string:
"Hello " * 0 # ''
"Hello " * (-100) # ''