Hulk
Hulk

Reputation: 34160

Split a string in python

          a="aaaa#b:c:"
          >>> for i in a.split(":"):
          ...   print i
          ...   if ("#" in i):   //i=aaaa#b
          ...     print only b

In the if loop if i=aaaa#b how to get the value after the hash.should we use rsplit to get the value?

Upvotes: 1

Views: 8615

Answers (6)

onaclov2000
onaclov2000

Reputation: 5841

I'd suggest from: Python Docs

str.rsplit([sep[, maxsplit]])

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.

so to answer your question yes.

EDIT:

It depends on how you wish to index your strings too, it looks like Rstring does it from the right, so if your data is always "rightmost" you could index by 0 (or 1, not sure how python indexes), every time, rather then having to do a size check of the returned array.

Upvotes: 1

tzot
tzot

Reputation: 95901

The following can replace your if statement.

for i in a.split(':'):
    print i.partition('#')[2]

Upvotes: 2

tKe
tKe

Reputation: 560

split would do the job nicely. Use rsplit only if you need to split from the last '#'.

a="aaaa#b:c:"
>>> for i in a.split(":"):
...   print i
...   b = i.split('#',1)
...   if len(b)==2:
...     print b[1]

Upvotes: -1

Ant
Ant

Reputation: 5404

do you really need to use split? split create a list, so isn't so efficient...

what about something like this:

>>> a = "aaaa#b:c:"
>>> a[a.find('#') + 1]
'b'

or if you need particular occurence, use regex instead...

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342263

>>> a="aaaa#b:c:"
>>> a.split(":",2)[0].split("#")[-1]
'b'

Upvotes: 1

Ruel
Ruel

Reputation: 15780

a = "aaaa#b:c:"
print(a.split(":")[0].split("#")[1])

Upvotes: 1

Related Questions