Strings: The Textual Heart of Python
In Python, strings are sequences of characters used to represent text. You can think of them as an ordered collection of letters, numbers, symbols, and spaces. To define a string, you enclose your text within:
Single quotes, double quotes
Python is flexible with strings. You can enclose them in eithers in single quotes '
or double quotes "
.
s1 = 'Hello world' # Single quotes
s2 = "Hello world" # Double quotes
The key is to be consistent, but there are times you’ll want to include one type of quote within a string enclosed by the other type.
s3 = "This is John's car." # Double quotes with a single quote inside
s4 = 'She said, "Hello!"' # Single quotes with double quotes inside
Triple quotes
For multiple-line of strings or strings containing both types of quotes, tripple quotes (either '
or "
) is convenient.
s5 = '''This string can have both 'single quotes' and "double quotes" without issues'''
s5 # Output: 'This string can have both \'single quotes\' and "double quotes" without issues'
str.format() and f-strings for string formatting
str.format()
: use curly braces as placeholders for values to be inserted.
name = 'Bob'
text = str.format('hello {}', name)
text # Output: 'Hello Bob'
f-strings
: Include variables directly within curly braces.
name = 'Alice'
text = f'Hello {name}'
text # 'Hello Alice'
Basic string operations
Indexing: access individual characters using square brackets and their position in the string
my_string = 'Hello world'
my_string[0] # Output: 'H
Splicing: extract a substring using a start and an end
my_string = 'Hello world'
my_string[0:5] # Output: 'Hello'
find()
: Returns the index of the first occurrence of a substring. Or return -1 if not found
sentence = "Learning Python is fun!"
position = sentence.find("Python")
position # Output: 9
index()
: Returns the index of the first occurrence of a substring. Or it raises an exception if not found.
sentence = "Learning Python is fun!"
position = sentence.index("Python")
position # Output: 9
position = sentence.index("Java") # Output: ValueError: substring not found
split()
: Splits a string into a list of substrings based on a delimiter
sentence = "Learning Python is fun!"
words = sentence.split()
words # Output: ['Learning', 'Python', 'is', 'fun!']
join()
: concatenat elements contained within an iterable object
words = ["Hello", "World"]
sentence = "-".join(words)
sentence # 'Hello-World'