Skip to content

Strings

Making a string

> mystr = ''
> mystr += 'a'
> mystr += 'b'
> mystr 
'ab'

Contains Value

if val in my_string

Character Checking

my_string.is
            alnum()   # Letters & Nums
            alpha()   # Letters
            numeric() # Numbers
            ascii()   # ASCII
            digit()   # Digits (Decimal is a Digit)
            decimal() # Decimal
            space()   # Whitespace
            upper()   # Upper
            lower()   # Lowercase

to [Letters & Num]

my_string = "a1b2c3d4e5"
[i for i in my_string if i.isalnum()]
['a', '1', 'b', '2', 'c', '3', 'd', '4', 'e', '5']

to [Characters]

[i for i in my_string if i.isalpha()]
['a', 'b', 'c', 'd', 'e']

to [Numbers]

[i for i in my_string if i.isnumeric()]
['1', '2', '3', '4', '5']

to Lowercase

my_string.lower()

to Uppercase

my_string.upper()

Reverse

my_string = 'abcdef'
my_string[::-1]
'fedcba'

Replace

my_string = 'abab'
my_string.replace("a", "B")
'BbBb'

Strip

> '   spacious   '.strip()
'spacious'
# The argument can be used to strip characters too
> 'www.example.com'.strip('cmowz.')
'example'

Sorting

Characters

sorted('cbdefa')
['a', 'b', 'c', 'd', 'e', 'f']
Numbers
sorted('9182736450')
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
Chars & Numbers
sorted('e1c23d4b50a')
['0', '1', '2', '3', '4', '5', 'a', 'b', 'c', 'd', 'e']

Eval

eval('1 + 4')
5

Normalize

my_string = " H e llo "
my_string.replace(" ", "".lower())
'Hello'

Characters

str -> int

int('3')
3

str -> ord

ord('z')
122

int -> str

chr(122)
'z'