When a program reads a name, sentence, file, or user response, it works with a string. A string is an ordered sequence of Unicode characters, so Python can iterate through it, index individual characters, search it with in, and extract parts with slices. Python has no separate character type: a single character is simply a string of length one. section 2.0
Use strings as both text values and sequences:
- Iterate directly over characters with for; use enumerate when the numeric index is also needed. section 1.18
- Search concisely with in, such as word[0] in 'aeiou', instead of repeating several comparisons. section 2.3
- Slice sequences with start, stop, and optional step values; for example, s[2:6] selects a range and s[::2] skips characters. section 2.3
- Remember that strings are immutable: operations produce new strings rather than changing existing characters in place. section 2.6
- Convert between textual and numeric data explicitly with int and str; input always returns a string, even when the user enters a number. section 1.3 section 1.22
Translate a word with sequence operations
def pig_latin(word): if word[0] in 'aeiou': return word + 'way' return word[1:] + word[0] + 'ay' print(pig_latin('air')) # airway print(pig_latin('python')) # ythonpay The function searches the first character, then combines slices and characters into a new string. It assumes a lowercase English word without punctuation, leaving capitalization and punctuation as useful extensions. section 2.2 section 2.3 section 2.6
Format text with values
name = 'world' x = 100 print(f'Hello, {name}') print(f'x * 2 = {x * 2}') F-strings place expressions directly inside braces. Older alternatives include %-formatting and str.format, which remain valid approaches but are more indirect in these examples. section 1.6
for index, one_letter in enumerate('abcd'):
print(f'{index}: {one_letter}')
Run the enumeration example to see Python return each character together with its index, contrasting direct sequence iteration with index-driven loops. section 1.18























