Strings

Strings are sequences of one or more characters—one of the most common data types.

Creating Strings

Enclose character sequences in single quotes (') or double quotes ("):

code.python
>>> a = 'Hello'
# Or
>>> a = "Hello"

For multi-line strings, use triple quotes (''' or """):

code.python
>>> a = '''Hello
Python'''
>>> a

'Hello\nPython' # \n is a newline character

Indexing and Slicing

Indexing extracts a single character from a string using []. Indexing is 0-based (left-to-right) or -1-based (right-to-left).

Example: Extract the 2nd character (index 1) and 2nd-last character (index -2) from 'abcdefg':

code.python
>>> a = 'abcdefg'
>>> a[1]   # 2nd character(0-based)
'b'
>>> a[-2]  # 2nd-last character(-1-based)
'f'

Slicing extracts a substring using start:end:step (follows the "left-closed, right-open" rule: includes start but excludes end).

Table 2-2 String Slicing Operations

Slicing Syntax Description Example Result
[:] Extract entire string 'abcde'[:] 'abcde'
[start:] Extract from start to end 'abcde'[2:] 'cde'
[:end] Extract from start to end-1 'abcde'[:2] 'ab'
[start:end] Extract from start to end-1 'abcde'[2:4] 'cd'
[start:end:step] Extract with step size step 'abcde'[1:4:2] 'bd'
[-n:] Extract last n characters 'abcde'[-3:] 'cde'
[-m:-n] Extract from -m-th to -(n+1)-th character 'abcde'[-4:-2] 'bc'
[:-n] Extract from start to -(n+1)-th character 'abcde'[:-1] 'abcd'
[::-s] Reverse extract with step s 'abcde'[::-1] 'edcba'

Length and Case Conversion

Python provides functions/methods for string length and case conversion (Table 2-3).

Table 2-3 Basic String Operations

Function/Method Description
len(str) Return the length of the string
str.upper() Convert all letters to uppercase
str.lower() Convert all letters to lowercase
str.capitalize() Capitalize the first letter, lowercase others
str.swapcase() Swap uppercase/lowercase letters

Splitting, Joining, and Trimming

Split: Use split(separator) to split a string into a list by a separator.

code.python
>>> 'a,b,c'.split(',')
['a', 'b', 'c']

Join: Use + or join() to concatenate strings.

code.python
>>> a = 'hello '
>>> b = 'python'
>>> a + b  # Concatenate with +
'hello python'
>>> ','.join(['hello', 'abc', 'python'])  # Join with separator
'hello,abc,python'

Trim: Use strip(), lstrip(), or rstrip() to remove leading/trailing characters.

Delete: Use del to delete the entire string.

code.python
>>> del a