Python Strings

Strings

Strings can be enclosed using single or double quotes. Strings are immutable.

Group = 'cad_faces'
Group = "cad_faces"

\ can be used to escape the quotes.

status = "doesn\'t match"
print(status)
Output
doesn't match

Strings can be Multiline

Use three double quotes or three single quotes.

str_multiline = """This is an example
for multiline strings."""
print(str_multiline)
Output
This is an example
for multiline strings.

Strings are Indexed

Strings are array of characters with the first character indexed with 0.

s = "SimLab"
print(s[0])
print(s[5])
Output
S
b

To count from the right, use negative indices

s = "SimLab"
print(s[-1])
print(s[-6])
Output
b
S

To get the sub string

s = "SimLab"
print(s[0:3])

Position 0 included to Position 3 excluded.

Output
Sim

String Methods

len()

Returns the length of the string.

s = "SimLab"
 len(s)
 Output
 6

strip()

Removes the white spaces in the beginning and the end of the string.

s = " SimLab "
s.strip()
Output
'SimLab'

lower() and upper()

Returns the string in lower and upper case.

s = "SimLab"
print(s.lower())
print(s.upper())
Output
simlab
SIMLAB

replace()

Replaces a string with another string.

scriptdir = "d:\projects\scripts"
scriptdir_r = scriptdir.replace("\\","/")
print(scriptdir)
print(scriptdir_r)
Output
d:\projects\scripts
d:/projects/scripts

split()

Splits the strings into substrings using the given separator.

xyz = "0,10,15"
xyz_split = xyz.split(",")
print(xyz_split)
print(xyz_split[0])
print(xyz_split[1])
print(xyz_split[2])
Output
['0', '10', '15']
0
10
15