I need to extract the word after the @
How can I do that? What I am trying:
text="Hello there @bob !"
user=text[text.find("@")+1:]
print user
output:
bob !
But the correct output should be:
bob
A regex solution for fun:
>>> import re
>>> re.findall(r'@(\w+)', '@Hello there @bob @!')
['Hello', 'bob']
>>> re.findall(r'@(\w+)', 'Hello there bob !')
[]
>>> (re.findall(r'@(\w+)', 'Hello there @bob !') or None,)[0]
'bob'
>>> print (re.findall(r'@(\w+)', 'Hello there bob !') or None,)[0]
None
The regex above will pick up patterns of one or more alphanumeric characters following an '@' character until a non-alphanumeric character is found.
Here's a regex solution to match one or more non-whitespace characters if you want to capture a broader range of substrings:
>>> re.findall(r'@(\S+?)', '@Hello there @bob @!')
['Hello', 'bob', '!']
Note that when the above regex encounters a string like @xyz@abc
it will capture xyz@abc
in one result instead of xyz
and abc
separately. To fix that, you can use the negated \s
character class while also negating @
characters:
>>> re.findall(r'@([^\s@]+)', '@xyz@abc some other stuff')
['xyz', 'abc']
And here's a regex solution to match one or more alphabet characters only in case you don't want any numbers or anything else:
>>> re.findall(r'@([A-Za-z]+)', '@Hello there @bobv2.0 @!')
['Hello', 'bobv']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With