A string is a sequence of characters (an ordered collection of characters), and is delimited by paired single or double quotes, e.g. "This is a string." It is a new type (str) for us. In this section, you will learn about the string data structure and how to work with it. In particular you will learn indexing and iteration.
Chapter 4: Strings
A string is a sequence of characters and is delimited by quotes.
a_string[i], indexing starts at 0, negative indexing starts from end.
a_string[x:y], a slice from index x up to but not including index y.
a_string[x:y:z], a slice from index x up to but not including index y with step z.
Defaults: no x, start slice at beginning; no y, end slice at end.
Idiom: a_string[::-1] is the reverse of a_string.
List of string methods
String Formatting: Tutorial .format()
String Formatting: Tutorial f-strings
year = 2024 stats = 'population' number = 345426571.56 percent = 4.2346 using_format = "the US{:5d}{:>11s} is estimated at {:,.1f} people\nwhich is equivalent to {:.2f}% of the world population".format(year, stats, number, percent) using_fstring = f"the US{year:5d}{stats:>11s} is estimated at {number:,.1f} people\nwhich is equivalent to {percent:.2f}% of the world population" print(using_format) print(using_fstring)the two print statements will result in the same string:
the US 2024 population is estimated at 345,426,571.6 people which is equivalent to 4.23% of the world population
for item in collection: suite-of-statements
We use uppercase characters to SHOUT when typing text. Let's write a program that converts every lowercase character to an uppercase character.
A palindrome is a string that is the same forwards and backwards. Case is ignored as are non-alphabetic and non-numeric characters. For example, "Madam, I'm Adam" is a palindrome.