1 Python Strings Flashcards
(14 cards)
How can I convert all my text to lowercase?
text = “NLP is POWERFUL!”
print(text.lower())
Output:”nlp is powerful!”
My sentence has unwanted spaces at the beginning or end. How do I clear them?
text = “ clean me “
print(text.strip())
Output:
“clean me”
I want to remove commas or change emojis to words.
text = “I love NLP, AI, and ML 💡”
cleaned = text.replace(“,”, “”).replace(“💡”, “[idea]”)
print(cleaned)
Output:
“I love NLP AI and ML [idea]”
How do I break my sentence into words?
text = “I love machine learning”
words = text.split()
print(words)
Output:
[‘I’, ‘love’, ‘machine’, ‘learning’]
I cleaned my words. How do I put them back into a sentence?
words = [‘nlp’, ‘is’, ‘awesome’]
sentence = “ “.join(words)
print(sentence)
Output:
“nlp is awesome”
I want to know where a word starts in a sentence.
text = “Python is everywhere”
print(text.find(“is”)) # Returns index
print(text.index(“Python”)) # Returns 0
Output:
7
0
I want to know how many times a word or letter appears.
text = “data data data science”
print(text.count(“data”))
Output:
3
I want to grab the first 5 characters or last 3 letters.
text = “language”
print(text[:5]) # First 5: “langu”
print(text[-3:]) # Last 3: “age”
How do I check if my sentence starts or ends with something?
text = “Natural Language Processing”
print(text.startswith(“Natural”))
print(text.endswith(“Processing”))
Output:
True
True
I want to check if a string is just letters, numbers, both, or only space.
print(“AI”.isalpha()) # True
print(“2024”.isdigit()) # True
print(“AI2024”.isalnum()) # True
print(“ “.isspace()) # True
How many characters are in my string?
text = “hello”
print(len(text))
Output: 5
zfill(width)
id = “7”
print(id.zfill(4))
Output: “0007”
More on find()
s = “hello world”
Finds the position of the substring “world”
print(s.find(“world”))
Returns -1 when substring is not found
print(s.find(“python”))
Finds the position of “o” starting from index 5
print(s.find(“o”, 5))
Output:
6
-1
7
More on index()
s = “hello world”
Finds position of the substring “world”
print(s.index(“world”))
Raises a ValueError when substring is not found
print(s.index(“python”))
Finds position of “o” starting from index 5
print(s.index(“o”, 5))
Output:
6
ERROR!
Traceback (most recent call last):
File “<main.py>", line 7, in <module>
ValueError: substring not found</module></main.py>
7
Note:
Use find() when we need to check if a substring exists and do not want to handle exceptions.
Use index() when we are sure that the substring exists or we want an exception to be raised if it doesn’t exist.