Career Enhancement Topic 2 String
Career Enhancement Topic 2 String
Reversing a String
Code-
s = "hello"
reversed_s = s[::-1]
print(reversed_s)
# Output : "olleh"
Code-
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam"))
# Output: True
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("hello"))
# Output: False
Code-
from collections import Counter
s = "abracadabra"
char_count = Counter(s)
print(char_count)
An anagram is when two strings have the same characters in a different order.
Code-
You can use dynamic programming to find the longest common substring between two strings.
Code-
print(longest_common_substring("abcde", "abfde"))
# Output: "ab"
To split a string into a list of substrings based on a delimiter, use split(). To join a list of
strings back into a single string, use join().
Code-
s = "apple,banana,cherry"
split_s = s.split(",")
print(split_s) # Output: ['apple', 'banana', 'cherry']
joined_s = "-".join(split_s)
print(joined_s) # Output: "apple-banana-cherry"
To find all occurrences of a substring in a string, you can use find() or a loop:
Code-
s = "abracadabra"
substring = "abra"
index = s.find(substring)
while index != -1:
print(f"Found at index: {index}")
index = s.find(substring, index + 1)
8. Replacing Substrings
You can replace all occurrences of a substring using the replace() method.
Code-
s = "abracadabra"
new_s = s.replace("abra", "xyz")
print(new_s)
# Output: "xyzcadxyz"
Code-
s = "hello world"
print("world" in s) # Output: True
print("python" in s) # Output: False