python - string总结
2020-10-11 本文已影响0人
Pingouin
Strings
- Strings are immutable.
- Strings are sequences.
- Strings have many methods. See Table 4.2.
- Standard operations:
- length function: len(s)
- membership:in
Indexing and Slicing
Given: s = 'Mississippi'
- Indexing starts at 0: s[0] is 'M'.
- Negative indices work backward from the end: s[-1] is 'i'.
- Slicing selects a subset up to but not including the final index: s[3:6] is 'sis'.
- Slicing default start is the beginning, so s[:4] is 'Miss'.
- Slicing default end is the end, so s[7:] is 'ippi'.
- Using both defaults makes a copy: s[:].
- Slicing’s optional third argument indicates step: s[:6:2] is 'Msi'.
- The idiom to reverse a string: s[::-1] is 'ippississiM'
Formatting
{arg:[[fill]align][sign][#][0][minimum width][,][.precision]type}
Iteration: for, enumerate
- for walks through each character in a string:
for ch in 'Mississippi':
- enumerate generates both the index and the character:
for index, ch in enumerate('Mississippi'):