Strings can be expressed using single quotes (') or double quotes (")
first_name = 'John'
last_name = "Doe"
about = 'John is 21 years old'
Characters in a string can be accessed using the standard [ ] syntax
print(first_name[0])
print(last_name[0])
print(len(first_name))
J D 4
Here are some other commonly used String methods.
1) s.lower(), s.upper() -- returns the lowercase or uppercase version of the string
2) s.strip() -- returns a string with whitespace removed from the start and end
3) s.isalpha()/s.isdigit()/s.isspace() -- tests if all the string chars are in the various character classes
4) s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given other string
5) s.find('other') -- searches for the given other string within s, and returns the first index where it begins or -1 if not found
6) s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new'
7) s.split('delim') -- returns a list of substrings separated by the given delimiter. As a convenient special case s.split() (with no arguments) splits on all whitespace chars.
9) s.join(list) -- opposite of split(). Joins the elements in the given list together using the string as the delimiter.
first_name.lower()
'john'
last_name.upper()
'DOE'
print(first_name.startswith('A'))
print(first_name.startswith('j'))
print(first_name.startswith('J'))
print(first_name.startswith('Jo'))
False False True True
print(about.find('o'))
print(about.find('u'))
1 -1
split_values = about.split()
split_values
['John', 'is', '21', 'years', 'old']
rejoin = ' '.join(split_values)
rejoin
'John is 21 years old'