Strings

From Training Material
Jump to navigation Jump to search


Accessing individual characters

Using square brackets, any character of a string can be accessed. The first character has the index 0.

s = 'Manipulating Strings'
print s[0] # first character
print s[3]
print s[-1] # last character
print s[-2] # second last

Creating substrings

Substrings can be formed by applying square brackets with two numbers inside separated by a colon. The second number is not included in the substring itself.

s = 'Manipulating Strings'
print s[1:6] # 'anipu'
Print s[9:13] # 'ing '
print s[0:2] # 'Ma'
print s[:3]
# 'Man'
print s[-4:] # 'ings'

Length of strings

Is returned as an integer by the len() function.

print len('Manipulating Strings')

String functions

There is a number of functions that can be used on every string variable.

s = 'Manipulating Strings '
Changing case:
s.upper()

s.lower()
Removing whitespace at both ends:
s.strip()
Cutting a string into columns:
s.split(' ')
Searching for substrings:
print s.find('ing')
Replacing substrings:
print s.replace('Strings','text')
Removing whitespace at both ends:
s.startswith('Man')

s.endswith('ings')