1
          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?

6 Answers 6

2

The following can replace your if statement.

for i in a.split(':'):
    print i.partition('#')[2]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

This assumes that i contains a '#'. split('#',1) and checking the length of the result would be safer.
1

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.

Comments

0

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...

Comments

-1

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.