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