Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python String Manipulation Techniques: Replacement, Deletion, Slicing, Concatenation, and More

Tech 1

Removing Whitespace and Special Characters

processed_text = text.strip().lstrip().rstrip(',')

String Duplication

# Original string duplication
original_string = 'duplicate_me'
copy_variable = original_string
original_string = 'modified_original'
print(copy_variable)  # Output: duplicate_me

String Concatenation

# Combining two strings
first_part = 'hello'
second_part = 'world'
first_part += second_part
print(first_part)  # Output: helloworld

Character Search

# Finding position of character
main_string = 'searchable'
target_char = 'e'
position_index = main_string.index(target_char)
print(position_index)  # Output: 1

String Comparison

# Comparing two strings
string_a = 'compare_this'
string_b = 'compare_these'
comparison_result = (string_a > string_b) - (string_a < string_b)
print(comparison_result)

Checking Character Containment

# Verifying if characters exist in string
base_string = '12345678'
check_chars = '456'
common_length = min(len(base_string), len(check_chars))
print(common_length)

String Length Calculation

# Getting string length
text_to_measure = 'length_calc'
print(len(text_to_measure))  # Output: 11

Case Conversion Operations

# Converting between upper and lower case
mixed_case_text = 'PyThOn CaSe'
uppercase_version = mixed_case_text.upper()
# lowercase_version = mixed_case_text.lower()
print(uppercase_version)  # Output: PYTHON CASE

Appending Limited-Length Substring

# Adding specific number of characters from another string
base_text = '12345'
extension = 'abcdef'
chars_to_add = 3
base_text += extension[:chars_to_add]
print(base_text)  # Output: 12345abc

Limited-Length String Comparison

# Comparing first n characters of two strings
first_string = '12345'
second_string = '123bc'
char_limit = 3
result = (first_string[:char_limit] > second_string[:char_limit]) - (first_string[:char_limit] < second_string[:char_limit])
print(result)

Copying Limited Characters

# Extracting specific number of characters
source_text = '12345'
chars_to_copy = 3
extracted_portion = source_text[:chars_to_copy]
print(extracted_portion)  # Output: 123

Replacing Initial Characters

# Replacing first n characters with specified character
original_text = '12345'
replacement_char = 'x'
num_replacements = 3
modified_text = replacement_char * num_replacements + original_text[num_replacements:]
print(modified_text)  # Output: xxx45

Character Set Scanning

# Finding first occurrence of any character from set
search_text = 'cekjgdklab'
char_set = 'gka'
found_position = -1
for character in search_text:
    if character in char_set:
        found_position = search_text.index(character)
        break
print(found_position)  # Output: 4

String Reversal

# Reversing string order
forward_string = 'abcdefg'
reversed_string = forward_string[::-1]
print(reversed_string)  # Output: gfedcba

Substring Search

# Finding substring within string
container_string = 'abcdefg'
target_substring = 'cde'
location = container_string.find(target_substring)
print(location)  # Output: 2

String Splitting

# Dividing string using delimiter
input_string = 'ab,cde,fgh,ijk'
delimiter = ','
remaining_after_first = input_string[input_string.find(delimiter) + 1:]
print(remaining_after_first)  # Output: cde,fgh,ijk

# Alternative approach
sample_text = 'ab,cde,fgh,ijk'
parts_list = sample_text.split(',')
print(parts_list)  # Output: ['ab', 'cde', 'fgh', 'ijk']

List-to-String Joining

separator = ','
country_list = ['Brazil', 'Russia', 'India', 'China']
combined_string = separator.join(country_list)
print(combined_string)  # Output: Brazil,Russia,India,China

Implementing PHP's addslashes Functionality

def escape_special_chars(input_str):
    escape_map = {'"': '\\"', "'": "\\'", "\0": "\\\\0", "\\": "\\\\"}
    return ''.join(escape_map.get(char, char) for char in input_str)

sample_input = "User 'Johnny' Smith (a.k.a. \"Captain Joe\")\\\\0"
print(sample_input)
print(escape_special_chars(sample_input))

Filtering Alphanumeric Characters Only

def keep_alphanum_only(input_str, replacement=''):
    normalized = input_str.lower()
    allowed_chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
    result = input_str
    for char in normalized:
        if char not in allowed_chars:
            result = result.replace(char, '')
    return result

print(keep_alphanum_only("test123 test-a"))  # Output: test123 testa

String Slicing Operations

data_string = '0123456789'
print(data_string[0:3])    # First three characters: 012
print(data_string[:])      # All characters: 0123456789
print(data_string[6:])     # From 7th to end: 6789
print(data_string[:-3])    # From start to third from end: 0123456
print(data_string[2])      # Third character: 2
print(data_string[-1])     # Last character: 9
print(data_string[::-1])   # Reverse: 9876543210
print(data_string[-3:-1])  # Third from end to one from end: 78
print(data_string[-3:])    # Last three: 789
print(data_string[:-5:-1]) # Last four in reverse: 9876

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.