Strings
What Are Strings?
- Strings in Python are sequences of characters surrounded by either single (
') or double (") quotation marks.
Examples:
Displaying strings with the
print()function:pythonprint("Hello") print('Hello')- Output:
Hello - Output:
Hello
- Output:
Quotes Inside Quotes:
You can use quotes inside a string as long as they don't match the quotes surrounding the string:
pythonprint("It's alright") print("He is called 'Johnny'") print('He is called "Johnny"')- Output:
It's alright - Output:
He is called 'Johnny' - Output:
He is called "Johnny"
- Output:
Assign String to a Variable:
Assigning a string to a variable:
pythona = "Hello" print(a)- Output:
Hello
- Output:
Multiline Strings:
You can assign a multiline string using three quotes:
pythona = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" print(a)- Output:
Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididuntut labore et dolore magna aliqua.
- Output:
Strings are Arrays:
Strings are arrays of bytes representing unicode characters. Access elements using square brackets:
pythona = "Hello, World!" print(a[1])- Output:
e
- Output:
String Length:
Use the
len()function to get the length of a string:pythona = "Hello, World!" print(len(a))- Output:
13
- Output:
Check String:
To check if a certain phrase or character is present in a string, use the
inkeyword:pythontxt = "The best things in life are free!" print("free" in txt)- Output:
True
- Output:
Summary:
- Strings in Python are versatile and widely used for text manipulation. Understanding how to create, access, and modify strings is fundamental for any programmer. Practice these examples and exercises to become proficient in working with strings in Python!