Python String

Working with string in Python


message = 'Hello World'



print(len(message)) # 11



print(message[0]) # H

print(message[10]) # d

print(message[-1]) # d (last char in the string)



print('String slicing:')



print(message[0:5]) # Hello

print(message[:5]) # Hello (Start from the first element if no index)



print(message[6:11]) # World

print(message[6:]) # World (End with the last element if no index)



print('String methods:')



print(message.lower()) # hello world

print(message.upper()) # HELLO WORLD



print(message.count('Hello')) # 1

print(message.count('l')) # 3



print(message.find('World')) # 6

print(message.find('Planet')) # -1



message_updated = message.replace('World', 'Planet')



print(message.startswith('Hello')) # True

print(message.endswith('World')) # True



print(message_updated) # Hello Planet



print('cats, dogs, parrots'.split(', ')) # ['cats', 'dogs', 'parrots']



spaces = '  Hello  '

print(spaces.strip()) # Hello



print('Convert to a string ((Casting to a string)):')

print(str(77)) # 77 as a string



print('Multiline string:')

multiline = '''Line one

Line two

Line three'''

print(multiline.split('\n')) # ['Line one', 'Line two', 'Line three']



print('Formatting a string:')



greet = 'Hello'

name = 'Jack'



greeting_1 = greet + ', ' + name + '!'

print(greeting_1) # Hello, Jack!



greeting_2 = '{}, {}!'.format(greet, name)

print(greeting_2) # Hello, Jack!



greeting_3 = f'{greet}, {name}!' # Works in Python 3.6 and above

print(greeting_3) # Hello, Jack!



print('In and not in for strings:')



print('Hello' in 'Hello World') # True

print('HELLO' in 'Hello World') # False

print('cats' not in 'cats and dogs') # False



print('Check type:')

print(isinstance(message, str)) # True

print(type(message)) # <class 'str'>



print('String info:+')

# print(dir(str)) # Show all the attributes and methods available for string class

# print(dir(message)) # Same as above

# print(help(len)) # Show help info on the method

# print(help(str.lower)) # Show help info on the method

Leave a Comment