If I have a list of strings, for example here's a small part of my list:

small_list=['HETATM 2142  O   DUM  2142     -26.000  -8.000  12.300','HETATM 2143  O   DUM  2143     -26.000  -6.000  12.300']

Is there a way to remove the 12.300 from a string in this list and then replace it with something else?

Dani AI

Generated

As described, the task is replacing the trailing numeric field in each string of a list. Both suggestions already given are valid: use a regular expression when you need a pattern match, and use a list comprehension to apply the change across the list (as noted by and ). Choose the method based on how your data is structured: use splitting/slicing for a last whitespace-separated token or fixed-width columns; use regex when spacing varies or you need to match numeric formats precisely.

Here is a simple, robust workflow using rsplit plus a list comprehension. This treats the last whitespace-separated token as the value to replace.

lines = ['rec A B 3.1415', 'rec C D 2.7182']

def replace_last_token(s, new):
    parts = s.rsplit(None, 1)
    return parts[0] + ' ' + new if len(parts) > 1 else new

new_lines = [replace_last_token(s, '0.000') for s in lines]

If you need to preserve exact spacing or match a floating-point pattern, a regex anchored to the end is better:

import re
pattern = re.compile(r'([+-]?\d+(?:\.\d+)?)\s*$')
new_lines = [pattern.sub('0.000', s) for s in lines]

Use a lambda in sub when you want to compute or format the replacement from the matched value. If the file uses fixed-width columns (not just whitespace-separated tokens), prefer slicing by column indices or a domain parser to avoid corrupting alignment. For reference see the Python re.sub and str.rsplit docs: re.sub docs str.rsplit docs.

Recommended Answers

All 2 Replies

List comprehension

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.