Previously, I learnt the attributes of different data types. - append, extend, pop, join for lists; split for strings.
- Today, I learnt more string attributes -
- capitalize, title, upper, lower
- index, find, search
- count
- startswith, endswith
- strip
- String index & String slicing
There are many ways to substring a string.
This is called ‘slicing’. Also can reverse a string. - Check if substring in string
- Iterate through a string or sub string
- Old method of string formatting using % (for reference only, I’ll be using f-strings instead)
Cheatsheets
What I learnt:
1. String Attributes
- For strings, I learnt how to use string.capitalize( ), string.title( ), string.upper( ), string.lower( ) attributes
x='hello there' print(x.title()) print(x.capitalize()) print(x.upper()) print(x.lower())
Output:
Hello There Hello there HELLO THERE hello there
- string.index( ), string.find( ), string.search( ) attributes
5 Ways to Find the Index of a Substring in Python- str.find()
- str.rfind()
- str.index()
- str.rindex()
- re.search()
- Using .index()
sentence = 'Python programming is fun.' result = sentence.index('is fun') print("Substring 'is fun':", result)
Output:
Substring 'is fun': 19
- Using .find()
"this is fun".find("fun")
Output:
8
- string.count( ) attribute
astring = "Hello world!" print(astring.count("l"))
Output:
3
- string.startswith( ), string.endswith( ) attribute
- Example 1:
astring = "Hello world!" print(astring.startswith("Hello")) print(astring.endswith("asdfasdfasdf"))
Output:
True False
- Example 2:
if "substring".startswith("sub"): print("substring starts with sub")
Output:
substring starts with sub
- Example 1:
- string.strip(‘chars’) attribute
string = ' xoxo love xoxo ' # Leading and trailing whitespaces are removed print(string.strip()) # All <whitespace>,x,o,e characters in the left and right of string are removed print(string.strip(' xoe')) # Argument doesn't contain space # No characters are removed. print(string.strip('stx')) # Argument doesn't contain space # 'an' is removed. string = 'android is awesome' print(string.strip('an'))
2. String index, String Slicing & Reversing a string
- string_name[index] to find character in the stated position.
- index can be negative from -1, -2 etc… to get character in the last position and so on working backwards.
student_name='Colette' if student_name[0].lower="c": print("Winner! Name starts with 'C'")
- string[start:end]
Get all characters from index start to end-1 - string[:end]
Get all characters from the beginning of the string to end-1 - string[start:]
Get all characters from index start to the end of the string - string[start:end:step]
- Example 1:
Get all characters from start to end-1 discountings = "Hey there! what should this string be?" print(f"Length of s = {len(s)}") print(f"The first occurrence of the letter a = {s.index('a')}") print(f"a occurs {s.count('a')} times") # Slicing the string into bits print(f"The first five characters are '{s[:5]}'") # Start to 5 print(f"The next five characters are '{s[5:10]}'") # 5 to 10 print(f"The thirteenth character is '{s[12]}'") # Just number 12 print(f"The characters with odd index are '{s[1::2]}'") #(0-based indexing)
Output:
Length of s = 38 The first occurrence of the letter a = 13 a occurs 1 times The first five characters are 'Hey t' The next five characters are 'here!' The thirteenth character is 'h' The characters with odd index are 'e hr!wa hudti tigb?'
- Example 2:
Read a string backwardsastring = "!figt" print(astring[::-1])
Output:
tgif!
- string[start:end]
3. Check if substring in string
if "fun" in "this is fun":
print("'this is fun' contains the word 'fun'.")
Output:
this is fun contains the word fun.
4. Iterate through a string or sub string
Use for variable_name in string_name or
for variable_name in string_name[x:x:x]
for item in her_name:
for letter in vegetable_name:
Thoughts
I managed to learn many new attributes of strings today, which is really great to know! String indexing and slicing is especially complicated due to the numbering(s) and I did read up more to learn more about how slice positions work.