Strings | Indexing, slicing, concatenation, and repetition

Strings represent text or bytes; this includes symbols and words, contents of text files loaded into memory, Internet addresses, source code, and so on.

Assign the string as a value of a variable

>>> name = "Dan Dumitrache"

Indexing Strings

Length of the string – built in function len().

>>> len(name)
14 #length of the string
>>> name[0]
'D'
>>> name[3]
' '
>>> name[-1]
'e'
>>> name[-2]
'h'
>>> name[0:3]
'Dan'

Slicing

>>> name[0:3]
'Dan'
>>> name[6:]
'mitrache'
>>> name[:6]
'Dan Du'
>>> name[5:11] #doesn't include 11
'umitra'
>>> name[:-1]
'Dan Dumitrach'
>>> name[:-4]
'Dan Dumitr'
>>> name[-8:-3]
'mitra'
>>> name[-3:-8]
''
>>> name[:]
'Dan Dumitrache'
>>>
>>> name = 'Dan Dumitrache'
>>> name[1:10:2]
'a uir'
>>>
>>> name[::-1]
'ehcartimuD naD'
>>>
>>> name[10:1:-2]
'atmDn'

Concatenation

#Adds two strings together to form another string
>>> name + ' Nicolae'
'Dan Dumitrache Nicolae'

Repetition

>>> name * 3
'Dan DumitracheDan DumitracheDan Dumitrache'

Create a new string from an existing string

>>> name
'Dan Dumitrache'
>>> new_name = name[:3] + ' Nicolae ' + name[4:]
>>> new_name
'Dan Nicolae Dumitrache'

Important!
Numbers, strings, and tuples are IMMUTABLE!
Lists, dictionaries, and sets are MUTABLE!

Leave a Reply