Python Forum

Full Version: find a character in a string in python3
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, how do I find a specific character in a string? for example, str="Hello world"
I need it to ba able to return the character "w", not just its index. Thanks.
What have you tried? How is it not working?
I am just wondering if there are some kinds of string functions in python like in php or javascript
The 'in' operator will tell you if one string exists within another one. The index and find methods of strings will tell you where in a string another string is. Regular expressions are supported through the re module.
Thanks for the reply.
when I use re.search, it returns something like this: <_sre.SRE_Match object; span=(6, 7), match='w'>.

Basically, I have serveral sensors output data throurgh serial to the pi. pi receives a serial stream string wt 30 C, now in my python script, I need it to be able to extract the device name and the value such as:

device=wt
value=30

How is this done in python? Thanks.
I guess that it's one string object like a log file?
# simulate a file
>>> data = '''\
... device=wt
... value=30'''

>>> d = {}
>>> for line in data.split('\n'):
...     device, value = line.split('=')
...     d[device] = value

# So it's now a dictionary
 >>> d
{'device': 'wt', 'value': '30'}
>>> d['value']
'30'
>>> d['device']
'wt'
(Sep-26-2017, 11:44 PM)tony1812 Wrote: [ -> ]I am just wondering if there are some kinds of string functions in python like in php or javascript

Yes.  Almost everything is an object in python, and any object is something you can inspect to get info about what's available to do with it.  Using strings as an example, you can see all the methods available using dir()
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
If you're not sure what one of those is, or if it takes arguments, the help() function can... help.
>>> help(str.find)
Help on method_descriptor:

find(...)
    S.find(sub[, start[, end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.

>>>
You can also help() the entire object, instead of one of it's methods/properties (although that's normally less helpful than just looking up the docs):
>>> help(str)
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |
 |  Methods defined here:
 |
 |  __add__(self, value, /)
 |      Return self+value.
 |
 |  __contains__(self, key, /)
 |      Return key in self.
 |
 |  __eq__(self, value, /)
 |      Return self==value.
 |
 |  __format__(...)
 |      S.__format__(format_spec) -> str
 |
 |      Return a formatted version of S as described by format_spec.
 |
 |  __ge__(self, value, /)
 |      Return self>=value.
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
-- More  --