First 4 characters
Write a Python program to get the first 4 characters of a string.
"Sqatools"
Sqat
Approach
- Slice
[:4].
Solution
print("Sqatools"[:4])Sqat
Learn the concept
New to this topic? Read the lesson, then come back.
Online Learning Platform
Python practice problems help beginners to become experts in a python programming language with a small amount of practice effort.
Write a Python program to get the first 4 characters of a string.
"Sqatools"
Sqat
[:4].print("Sqatools"[:4])Sqat
New to this topic? Read the lesson, then come back.
Write a Python program to find the words longer than a given length.
length = 3, text = "We are learning python"
learning python
len(w) > n.n = 3text = "We are learning python"print(" ".join(w for w in text.split() if len(w) > n))learning python
New to this topic? Read the lesson, then come back.
Write a Python program that repeats each vowel 3 times and each consonant 2 times, leaving spaces alone.
"Sqa Tools Learning"
SSqqaaa TToooooollss LLeeeaaarrnniiinngg
text = "Sqa Tools Learning"out = []for ch in text: if ch.lower() in "aeiou": out.append(ch * 3) elif ch.isalpha(): out.append(ch * 2) else: out.append(ch)print("".join(out))SSqqaaa TToooooollss LLeeeaaarrnniiinngg
Building a list and joining once is faster than adding to a string in a loop.
New to this topic? Read the lesson, then come back.
Write a Python program to replace the second occurrence of every character with “$”.
"Programming"
Prog$am$in$
text = "Programming"seen = {}result = ""for ch in text: seen[ch] = seen.get(ch, 0) + 1 result += "$" if seen[ch] == 2 else chprint(result)Prog$am$in$
Count each character as it appears.
Only the exact second occurrence becomes “$”; the third “m” or “g” would stay.
New to this topic? Read the lesson, then come back.
Write a Python program to find the character that repeats most times in a row (consecutively) in a string.
"aabbbbcccdd"
b 4
text = "aabbbbcccdd"best_char, best_len = text[0], 1run_len = 1for i in range(1, len(text)): if text[i] == text[i - 1]: run_len += 1 else: run_len = 1 if run_len > best_len: best_char, best_len = text[i], run_lenprint(best_char, best_len)b 4
The run grows while characters repeat and resets on a change.
Save the run if it is the longest so far.
itertools.groupby(text) groups consecutive equal characters for you.
New to this topic? Read the lesson, then come back.
Write a Python program to find the least frequent character in a string.
"abcdabdggfhf"
c Counter({'a': 2, 'b': 2, 'd': 2, 'g': 2, 'f': 2, 'c': 1, 'h': 1})from collections import Counter text = "abcdabdggfhf"counts = Counter(text)print(min(counts, key=counts.get), counts)c Counter({'a': 2, 'b': 2, 'd': 2, 'g': 2, 'f': 2, 'c': 1, 'h': 1})key=counts.get compares characters by their counts; with ties, the first seen wins.
New to this topic? Read the lesson, then come back.
Write a Python program to count how many times a whole word occurs in a string.
"food" in "I want to eat fast food"; "are" in "We are learning Python, wow are you"
1 2
def count_word(text, word): return sum(1 for w in text.split() if w.strip(",.!?") == word) print(count_word("I want to eat fast food", "food"))print(count_word("We are learning Python, wow are you", "are"))1 2
Counting whole words avoids matching “are” inside “hare”.
New to this topic? Read the lesson, then come back.
Write a Python program to find the position (word number, starting at 1) of a word in a sentence.
word = "problems", text = "I am solving problems based on strings"
word number: 4 character index: 13
index(); add 1 for a human-friendly position.text = "I am solving problems based on strings"word = "problems"words = text.split()print("word number:", words.index(word) + 1)print("character index:", text.find(word))word number: 4 character index: 13
List indexes start at 0, so add 1.
find() gives the character position instead.
New to this topic? Read the lesson, then come back.
Write a Python program to convert number words into a number.
"five four three two one"
54321
words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]text = "five four three two one"digits = "".join(str(words.index(w)) for w in text.split())print(int(digits))54321
words.index(w) is the digit for each word.
New to this topic? Read the lesson, then come back.
Write a Python program to format a float to 3 decimal places and convert it to a string.
2.14652
2.147 str
.3f.x = 2.14652text = f"{x:.3f}"print(text, type(text).__name__)2.147 str
Formatting rounds, so 2.14652 becomes “2.147”, not “2.146” as the original sample showed. Use str(int(x * 1000) / 1000) if you need to cut off digits instead.
New to this topic? Read the lesson, then come back.