I'm trying to figure this out, but every google I do just brings up garbage.

What I'm trying to do is split a string at an *

I want the string to be in 2 parts basically. So..

Say the string is 2478*72-432*823-74

What I want to do is split it right after the first * and have the 2 new strings as new strings

So it would be:

given = F4K8*72-432*82T-74

split given @ *

part1 = F4K8*
part2 = 72-432*82T-74

Dani AI

Generated

Both and gave correct, practical ways (find+slice and split with maxsplit). chose ’s approach — here's a concise alternative and a few edge-case tips that make the code more robust and easier to read.

A cleaner built-in is str.partition, which always returns a 3-tuple (before, sep, after). Because it returns the separator as the middle element you don’t need to re-add '*' afterwards, and its return values make it easy to detect “no separator found” without risking an index error:

s = 'F4K8*72-432*82T-74'
left, sep, right = s.partition('*')
part1 = left + sep   # includes '*' when present
part2 = right
# if sep == '' then no '*' was found (partition returned (s, '', ''))

If the goal is to split at the last *, use rpartition (same idea but splits at the final occurrence). Handle the sep == '' case explicitly when the separator might be absent. Also consider the case where the string starts with * (left will be empty, sep will be '*') so part1 may be just '*'.

If you need to ignore escaped asterisks (e.g., \*) or split by the first unescaped *, a regex with a negative lookbehind works; use re.split(r'(?<!\\)\*', s, 1) and check the result length before unpacking. These options avoid manual index arithmetic and make the intent clearer to future readers.

Recommended Answers

All 3 Replies

Try this:

string = 'F4K8*72-432*82T-74'
index = string.find('*')
part1 = string[0:index+1]
part2 = string[index+1:len(string)]
# string[startIndex:endIndex]
print 'Part1: ' + part1
print 'Part2: ' + part2

You could split the string once ...

mystr = "F4K8*72-432*82T-74"

mylist = mystr.split("*", 1)

print mylist   # ['F4K8', '72-432*82T-74']

# add the missing '*' back in
print "part1 = %s*" % mylist[0]
print "part2 = %s" % mylist[1]

Thanks guys! I'm using the first response. You can see the program I wrote here:

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.