Python Strings
Strings in Python
In Python, strings are sequences of characters enclosed in either single ('
) or double ("
) quotation marks. Both are treated the same.
python
1print("Hello")
2print('Hello')
Quotes Inside Strings
You can use quotes inside a string as long as they do not match the surrounding quotes:
python
1print("It's alright") # Single quote inside double quotes
2print('He is called "Johnny"') # Double quote inside single quotes
Python Assign String Variables
You can assign a string to a variable by using the equal sign (=
):
python
1a = "Hello"
2print(a)
Python multiline strings
To assign a multiline string, use three single ('''
) or double quotes ("""
):
python
1a = """Lorem ipsum dolor sit amet,
2consectetur adipiscing elit,
3sed do eiusmod tempor incididunt
4ut labore et dolore magna aliqua."""
5print(a)
6
7b = '''Lorem ipsum dolor sit amet,
8consectetur adipiscing elit.'''
9print(b)
The line breaks are preserved in the output.
Python String Length
To get the length of a string, use the len()
function:
python
1a = "Hello, World!"
2print(len(a)) # Output: 13
Check if a Substring is Present
Use the in
keyword to check if a substring exists within a string:
python
1txt = "The best things in life are free!"
2print("free" in txt) # Output: True
Check if NOT Present
To check if a substring is not present, use the not in
keyword:
python
1txt = "The best things in life are free!"
2print("expensive" not in txt) # Output: True
Python Slicing Strings
You can slice a string by specifying a start and an end index, separated by a colon:
python
1b = "Hello, World!"
2print(b[2:5]) # Output: 'llo'
- Slice from the start: Omit the start index to begin at the first character.
python
1print(b[:5]) # Output: 'Hello'
- Slice to the end: Omit the end index to go to the end of the string.
python
1print(b[2:]) # Output: 'llo, World!'
- Negative indexing: Use negative numbers to start slicing from the end of the string.
python
1print(b[-5:-2]) # Output: 'orl'