Skip to content

Instantly share code, notes, and snippets.

@Nagasaki45
Last active August 29, 2015 14:00
Show Gist options
  • Save Nagasaki45/11380356 to your computer and use it in GitHub Desktop.
Save Nagasaki45/11380356 to your computer and use it in GitHub Desktop.

Common string operations

Checks

method examples
endswith / startswith 'hello world'.startswith('he') # -> True
isalnum / isalpha / isdigit / islower / isupper / isspace

'123'.isdigit() # -> True

'Hello World'.islower() # -> False

Searches

method examples
count 'hello world'.count('l') # -> 3
find

'hello world'.find('l') # -> 2

'hello world'.find('t') # -> -1

index Same as find but raises exception if can't find

Manipulations

Be aware that str is an immutable type. All the methods bellow return new string (no in place operations).

method examples
lower / upper / title / capitalize / swapcase

'hello world'.title() # -> 'Hello World'

'hello world'.capitalize() # -> 'Hello world'

replace 'hello world'.replace('world', 'john') # -> 'hello john'
strip (/ rstrip / lstrip) Removes spaces and new lines from the ends of a string

Split and join

method examples
split (/ rsplit)

'hello world'.split() # -> ['hello', 'world']

'hello, and welcome'.split(', ') # -> ['hello', 'and welcome']

splitlines Similar to split('\n'). Read the docs for more info.
join

' '.join(['hello', 'world']) # -> 'hello world'

'<br >'.join(['first line', 'second line']) # -> 'first line<br >second line'

Formatting

A blog post about string formatting

All you will ever need for formating a string.

pyformat.info

More string formatting info. Comparing old and new style formatting.

Further reading

Google educational resources

Basic information about string indexing, slicing and a bit further.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment