Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Working with String Data in Python

Tech 1

String literals in Python are created using quotation marks and can contain digits, letters, Chinese characters, and special symbols.

Defining Strings

example_str1 = 'Python Programming'
example_str2 = "Python Programming"
example_str3 = '''Python Programming'''

Triple quotes allow for strings to span multiple lines, which is useful for long text without needing concatenation.

multi_line = '''Line one
Line two
Line three'''

Indexing

Indexing, or subscripting, accesses a specific character within a string. Indices start at 0.

# character_variable[index]
my_string = "data123"
print(my_string[0])  # Output: 'd'

Slicing

Slicing extracts a portion of a sequence, applicable to strings, lists, and tuples.

Syntax: variable_name[start:stop:step]

  • start: Start index.
  • stop: End index.
  • step: Stride, default is 1.

Note:

  • The slice does not include the character at the stop index.
  • Parameters can be positive or negative integers; negative values indicate slicing from the end.
text = 'example text'
print(text[:5])     # 'examp'
print(text[3:])     # 'ple text'
print(text[::-1])   # 'txet elpmaxe'
print(text[0:4])    # 'exam'

Searching Strings

These methods locate a substring within a string.

find(substring, start, end)

Checks if a substring exists. Returns the starting index if found, otherwise -1.

text = 'example text'
print(text.find("m"))       # Output: 2
print(text.find("m", 5))    # Output: -1 (searches from index 5 onward)

index(substring, start, end)

Similar to find(), but raises a ValueError if the substring is not found.

text = 'example text'
print(text.index("m"))       # Output: 2
# print(text.index("m", 5))  # Would raise ValueError

rfind(substring, start, end)

Performs a search from the end of the string (right-to-left). Returns the index if found, otherwise -1.

text = 'example text'
print(text.rfind("e"))      # Output: 9
print(text.rfind("e", 0, 5)) # Output: 0

rindex(substring, start, end)

Right-to-left version of index(). Raises ValueError on failure.

count(substring, start, end)

Returns the number of non-overlapping occurrences of a substring.

text = 'example text'
print(text.count("e"))      # Output: 3
print(text.count("ex"))     # Output: 1

Modifying Strings

String methods return modified copies; the original string remains unchanged.

replace(old, new, count)

Replaces occurrences of a substring.

text = 'example text'
print(text.replace("e", "E", 1))  # Replaces first 'e' only

split(separator, maxsplit)

Splits a string into a list based on a separator.

text = 'example text'
print(text.split(" "))  # ['example', 'text']

join(iterable)

Concatenates elements of an iterable (e.g., list, tuple) using the string as a separator.

parts = ['example', 'text']
separator = "-"
print(separator.join(parts))  # 'example-text'

capitalize()

Converts the first character to uppercase and the rest to lowercase.

print('hello WORLD'.capitalize())  # 'Hello world'

title()

Capitalizes the first letter of each word.

print('hello world'.title())  # 'Hello World'

lower() and upper()

Converts all characters to lowercase or uppercase.

print('Hello World'.lower())  # 'hello world'
print('Hello World'.upper())  # 'HELLO WORLD'

lstrip(), rstrip(), strip()

Removes leading (lstrip), trailing (rstrip), or both leading and trailing (strip) whitespace.

text = '  Hello World  '
print(text.lstrip())  # 'Hello World  '
print(text.rstrip())  # '  Hello World'
print(text.strip())   # 'Hello World'

ljust(width, fillchar), rjust(width, fillchar), center(width, filchar)

Returns a padded string aligned left, right, or center. The fillchar must be a single character.

text = 'Hello'
print(text.ljust(10, '*'))  # 'Hello*****'
print(text.rjust(10, '*'))  # '*****Hello'
print(text.center(10, '*')) # '**Hello***'

String Validation Methods

startswith(prefix, start, end) and endswith(suffix, start, end)

Checks if the string starts or ends with the specified substring. Returns True or False.

isalpha()

Returns True if all characters are alphabetic and there is at least one character.

isdigit()

Returns True if all characters are digits and there is at least one character.

isspace()

Returns True if the string contains only whitespace characters.

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.