1 Python Strings Flashcards
(12 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”