Search This Blog

Tuesday, October 10, 2023

Python string

 Python provides a wide range of built-in functions and methods for working with strings. Here is a list of some commonly used string functions and methods:


len(): Returns the length of the string.


python

Copy code

s = "Hello, World!"

length = len(s)  # length is 13

str(): Converts a value to a string.


python

Copy code

num = 42

s = str(num)  # s is "42"

concatenation: Combining strings using the + operator.


python

Copy code

s1 = "Hello"

s2 = "World"

s3 = s1 + ", " + s2  # s3 is "Hello, World"

format(): Format a string using placeholders.


python

Copy code

name = "Alice"

age = 30

s = "My name is {} and I am {} years old.".format(name, age)

f-strings (formatted string literals): A more concise way to format strings using f-strings (Python 3.6+).


python

Copy code

name = "Alice"

age = 30

s = f"My name is {name} and I am {age} years old."

strip(): Removes leading and trailing whitespace.


python

Copy code

s = "   Hello, World!   "

s = s.strip()  # s is now "Hello, World!"

split(): Splits a string into a list based on a delimiter.


python

Copy code

s = "apple,banana,cherry"

fruits = s.split(",")  # fruits is ["apple", "banana", "cherry"]

join(): Joins a list of strings into a single string using a delimiter.


python

Copy code

fruits = ["apple", "banana", "cherry"]

s = ",".join(fruits)  # s is "apple,banana,cherry"

find(): Searches for a substring and returns its index or -1 if not found.


python

Copy code

s = "Hello, World!"

index = s.find("World")  # index is 7

replace(): Replaces all occurrences of a substring with another string.


python

Copy code

s = "Hello, World!"

new_s = s.replace("World", "Python")  # new_s is "Hello, Python!"

upper(): Converts all characters to uppercase.


python

Copy code

s = "Hello, World!"

upper_s = s.upper()  # upper_s is "HELLO, WORLD!"

lower(): Converts all characters to lowercase.


python

Copy code

s = "Hello, World!"

lower_s = s.lower()  # lower_s is "hello, world!"

startswith() and endswith(): Checks if a string starts or ends with a specified substring.


python

Copy code

s = "Hello, World!"

starts_with = s.startswith("Hello")  # True

ends_with = s.endswith("World")  # True

count(): Counts the number of occurrences of a substring in a string.


python

Copy code

s = "Hello, World!"

count = s.count("l")  # count is 3

isalpha(), isdigit(), isalnum(): Check if the string consists of alphabetic characters, digits, or alphanumeric characters.


python

Copy code

s1 = "Hello"

s2 = "123"

s3 = "Hello123"

is_alpha = s1.isalpha()  # True

is_digit = s2.isdigit()  # True

is_alnum = s3.isalnum()  # True


isupper() and islower(): Check if all characters in the string are uppercase or lowercase, respectively.


python

Copy code

s1 = "HELLO"

s2 = "world"

is_upper = s1.isupper()  # True

is_lower = s2.islower()  # True

capitalize(): Converts the first character of the string to uppercase and the rest to lowercase.


python

Copy code

s = "hello world"

capitalized_s = s.capitalize()  # "Hello world"

title(): Converts the first character of each word in the string to uppercase.


python

Copy code

s = "hello world"

title_s = s.title()  # "Hello World"

swapcase(): Swaps the case of all characters in the string.


python

Copy code

s = "Hello, World!"

swapped_s = s.swapcase()  # "hELLO, wORLD!"

isnumeric() and isdecimal(): Check if all characters in the string are numeric or decimal digits, respectively.


python

Copy code

s1 = "12345"

s2 = "12.34"

is_numeric = s1.isnumeric()  # True

is_decimal = s2.isdecimal()  # False

isprintable(): Check if all characters in the string are printable (e.g., not control characters).


python

Copy code

s = "Hello, World!"

is_printable = s.isprintable()  # True

zfill(): Pads the string with zeros on the left until it reaches a specified width.


python

Copy code

s = "42"

padded_s = s.zfill(5)  # "00042"

rjust() and ljust(): Right-justifies or left-justifies the string within a specified width, padding with a specified character.


python

Copy code

s = "42"

rjust_s = s.rjust(5, "0")  # "00042"

ljust_s = s.ljust(5, "0")  # "42000"

center(): Centers the string within a specified width, padding with a specified character.


python

Copy code

s = "42"

centered_s = s.center(5, "0")  # "00420"

encode(): Encodes the string into bytes using a specified encoding.


python

Copy code

s = "Hello, World!"

encoded_bytes = s.encode("utf-8")

startswith() and endswith(): Check if a string starts or ends with a specified substring.


python

Copy code

s = "Hello, World!"

starts_with = s.startswith("Hello")  # True

ends_with = s.endswith("World")  # True


commonly asked python string interview questions with answer


ChatGPT

Certainly! Here are some commonly asked Python string interview questions along with their answers:


Reverse a String:

Q: Write a Python function to reverse a string.


python

Copy code

def reverse_string(input_str):

    return input_str[::-1]

Check for Palindrome:

Q: Write a Python function to check if a string is a palindrome.


python

Copy code

def is_palindrome(input_str):

    return input_str == input_str[::-1]

Count Occurrences:

Q: Write a Python function to count the occurrences of a substring in a given string.


python

Copy code

def count_substring_occurrences(input_str, substring):

    return input_str.count(substring)

Anagram Detection:

Q: Write a Python function to check if two strings are anagrams of each other.


python

Copy code

def are_anagrams(str1, str2):

    return sorted(str1) == sorted(str2)

String Compression:

Q: Write a Python function to perform basic string compression using the counts of repeated characters.


python

Copy code

def compress_string(input_str):

    compressed = ""

    count = 1

    for i in range(1, len(input_str)):

        if input_str[i] == input_str[i - 1]:

            count += 1

        else:

            compressed += input_str[i - 1] + str(count)

            count = 1

    compressed += input_str[-1] + str(count)

    return compressed if len(compressed) < len(input_str) else input_str

String Rotation:

Q: Write a Python function to check if one string is a rotation of another.


python

Copy code

def is_rotation(str1, str2):

    if len(str1) != len(str2):

        return False

    return str2 in (str1 + str1)

Longest Common Prefix:

Q: Write a Python function to find the longest common prefix of a list of strings.


python

Copy code

def longest_common_prefix(strs):

    if not strs:

        return ""

    common_prefix = min(strs)

    for i, char in enumerate(common_prefix):

        for string in strs:

            if string[i] != char:

                return common_prefix[:i]

    return common_prefix

String to Integer (atoi):

Q: Implement the atoi function, which converts a string to an integer.


python

Copy code

def atoi(s):

    s = s.strip()

    if not s:

        return 0

    sign = -1 if s[0] == '-' else 1

    if s[0] in ('-', '+'):

        s = s[1:]

    result = 0

    for char in s:

        if not char.isdigit():

            break

        result = result * 10 + int(char)

    return max(min(result * sign, 2**31 - 1), -2**31)

These are some common Python string interview questions and their corresponding answers. These questions cover a range of string manipulation techniques and can help you prepare for interviews that involve string manipulation in Python.


Certainly! Here are some more tricky Python string interview questions along with their answers:

  1. First Non-Repeating Character: Q: Write a Python function to find the first non-repeating character in a string.

    python
    def first_non_repeating_char(s): char_count = {} for char in s: char_count[char] = char_count.get(char, 0) + 1 for char in s: if char_count[char] == 1: return char return None
  2. Valid Parentheses: Q: Write a Python function to check if a given string containing parentheses is valid.

    python
    def is_valid_parentheses(s): stack = [] brackets = {')': '(', '}': '{', ']': '['} for char in s: if char in brackets.values(): stack.append(char) elif char in brackets.keys(): if not stack or stack.pop() != brackets[char]: return False else: return False return not stack
  3. Longest Substring Without Repeating Characters: Q: Write a Python function to find the length of the longest substring without repeating characters.

    python
    def length_of_longest_substring(s): char_index = {} max_length = start = 0 for i, char in enumerate(s): if char in char_index and char_index[char] >= start: start = char_index[char] + 1 char_index[char] = i max_length = max(max_length, i - start + 1) return max_length
  4. String Permutations: Q: Write a Python function to generate all permutations of a given string.

    python
    from itertools import permutations def string_permutations(s): return [''.join(p) for p in permutations(s)]
  5. Implement strStr(): Q: Implement the strStr() function, which finds the index of the first occurrence of a substring in another string.

    python
    def strStr(haystack, needle): if not needle: return 0 for i in range(len(haystack) - len(needle) + 1): if haystack[i:i+len(needle)] == needle: return i return -1
  6. Group Anagrams: Q: Given a list of strings, group anagrams together.

    python
    from collections import defaultdict def group_anagrams(strs): grouped = defaultdict(list) for s in strs: key = ''.join(sorted(s)) grouped[key].append(s) return list(grouped.values())
  7. Decode String: Q: Given an encoded string, return its decoded string.

    python
    def decode_string(s): stack = [] curr_num = 0 curr_str = "" for char in s: if char.isdigit(): curr_num = curr_num * 10 + int(char) elif char == '[': stack.append((curr_str, curr_num)) curr_str, curr_num = "", 0 elif char == ']': prev_str, num = stack.pop() curr_str = prev_str + curr_str * num else: curr_str += char return curr_str

These tricky Python string interview questions cover more advanced string manipulation techniques and problem-solving skills. They are designed to challenge your understanding of strings and algorithms.


Certainly! Here are some more challenging Python string interview questions along with their answers:

  1. Valid Palindrome II: Q: Given a non-empty string s, you may delete at most one character. Write a Python function to check if you can make it a palindrome.

    python
    def valid_palindrome(s): def is_palindrome(s, left, right): while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True left, right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return is_palindrome(s, left + 1, right) or is_palindrome(s, left, right - 1) left += 1 right -= 1 return True
  2. Minimum Window Substring: Q: Given two strings S and T, find the minimum window in S that will contain all the characters in T.

    python
    def min_window_substring(s, t): from collections import Counter t_counter = Counter(t) required_chars = len(t) left = right = 0 min_len = float('inf') min_window = "" while right < len(s): if s[right] in t_counter: if t_counter[s[right]] > 0: required_chars -= 1 t_counter[s[right]] -= 1 while required_chars == 0: if right - left + 1 < min_len: min_len = right - left + 1 min_window = s[left:right + 1] if s[left] in t_counter: t_counter[s[left]] += 1 if t_counter[s[left]] > 0: required_chars += 1 left += 1 right += 1 return min_window
  3. Regular Expression Matching: Q: Implement regular expression matching with support for '.' and '*'.

    python
    def is_match(s, p): if not p: return not s first_match = bool(s) and (s[0] == p[0] or p[0] == '.') if len(p) >= 2 and p[1] == '*': return (is_match(s, p[2:]) or (first_match and is_match(s[1:], p))) else: return first_match and is_match(s[1:], p[1:])
  4. Longest Substring with At Most K Distinct Characters: Q: Given a string s and an integer k, return the length of the longest substring with at most k distinct characters.

    python
    def length_of_longest_substring_k_distinct(s, k): from collections import defaultdict max_length = 0 left = 0 char_count = defaultdict(int) for right in range(len(s)): char_count[s[right]] += 1 while len(char_count) > k: char_count[s[left]] -= 1 if char_count[s[left]] == 0: del char_count[s[left]] left += 1 max_length = max(max_length, right - left + 1) return max_length

These advanced Python string interview questions require a deeper understanding of string manipulation, algorithms, and problem-solving skills. They are designed to challenge your ability to tackle complex string-related problems.


Certainly! Here are more Python string interview questions:

  1. Valid Number: Q: Write a Python function to determine if a given string is a valid number (integer or floating-point).

    python
    def is_valid_number(s): try: float(s) return True except ValueError: return False
  2. Reverse Words in a String: Q: Write a Python function to reverse the words in a string while preserving the order of words.

    python
    def reverse_words(s): words = s.split() reversed_str = ' '.join(reversed(words)) return reversed_str
  3. Longest Substring Without Repeating Characters (with k distinct characters): Q: Modify the previous "Longest Substring with At Most K Distinct Characters" question to return the actual substring itself.

    python
    def longest_substring_k_distinct(s, k): from collections import defaultdict max_length = 0 left = 0 char_count = defaultdict(int) start_index = 0 for right in range(len(s)): char_count[s[right]] += 1 while len(char_count) > k: char_count[s[left]] -= 1 if char_count[s[left]] == 0: del char_count[s[left]] left += 1 if right - left + 1 > max_length: max_length = right - left + 1 start_index = left return s[start_index:start_index + max_length]
  4. Add Binary Strings: Q: Given two binary strings, return their sum (also a binary string).

    python
    def add_binary(a, b): carry = 0 result = [] i, j = len(a) - 1, len(b) - 1 while i >= 0 or j >= 0 or carry: sum = carry if i >= 0: sum += int(a[i]) i -= 1 if j >= 0: sum += int(b[j]) j -= 1 carry = sum // 2 result.append(str(sum % 2)) return ''.join(result[::-1])
  5. Longest Palindromic Substring: Q: Find the longest palindromic substring in a given string.

    python
    def longest_palindromic_substring(s): def expand_around_center(left, right): while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return s[left + 1:right] longest = "" for i in range(len(s)): # Odd length palindrome palindrome1 = expand_around_center(i, i) if len(palindrome1) > len(longest): longest = palindrome1 # Even length palindrome palindrome2 = expand_around_center(i, i + 1) if len(palindrome2) > len(longest): longest = palindrome2 return longest

These additional Python string interview questions will further test your problem-solving skills and ability to work with strings in various scenarios.

  1. String Reversal Without Built-in Functions: Q: Write a Python function to reverse a string without using any built-in string reversal functions (e.g., slicing).

    python
    def reverse_string(input_str): reversed_str = "" for char in input_str: reversed_str = char + reversed_str return reversed_str
  2. Check for Anagrams: Q: Write a Python function to check if two strings are anagrams of each other without using any built-in sorting functions.

    python
    def are_anagrams(str1, str2): if len(str1) != len(str2): return False char_count = {} for char in str1: if char in char_count: char_count[char] += 1 else: char_count[char] = 1 for char in str2: if char in char_count: char_count[char] -= 1 if char_count[char] < 0: return False else: return False return True
  3. Count Vowels and Consonants: Q: Write a Python function to count the number of vowels and consonants in a given string.

    python
    def count_vowels_and_consonants(input_str): vowels = "aeiouAEIOU" vowel_count = 0 consonant_count = 0 for char in input_str: if char.isalpha(): if char in vowels: vowel_count += 1 else: consonant_count += 1 return vowel_count, consonant_count
  4. Check for Pangram: Q: Write a Python function to check if a given string is a pangram (contains every letter of the alphabet at least once).

    python
    def is_pangram(input_str): alphabet = "abcdefghijklmnopqrstuvwxyz" return all(char in input_str.lower() for char in alphabet)
  5. String Compression: Q: Write a Python function to perform basic string compression by replacing consecutive repeating characters with the character followed by the count.

    python
    def compress_string(input_str): compressed = "" count = 1 for i in range(1, len(input_str)): if input_str[i] == input_str[i - 1]: count += 1 else: compressed += input_str[i - 1] + str(count) count = 1 compressed += input_str[-1] + str(count) return compressed if len(compressed) < len(input_str) else input_str

These simple yet tricky Python string interview questions are designed to test your understanding of string manipulation techniques and problem-solving skills with a twist.