Python Forum
find a character in a string in python3
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
find a character in a string in python3
#1
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.
Reply
#2
What have you tried? How is it not working?
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
I am just wondering if there are some kinds of string functions in python like in php or javascript
Reply
#4
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
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.
Reply
#6
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'
Reply
#7
(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  --
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python3 string slicing Luchano55 4 533 Feb-17-2024, 09:40 AM
Last Post: Pedroski55
  use of escape character in re.sub and find WJSwan 1 876 Feb-16-2023, 05:19 PM
Last Post: Larz60+
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,305 Sep-27-2022, 01:38 PM
Last Post: buran
  Find and Replace numbers in String giddyhead 2 1,197 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  Regex: a string does not starts and ends with the same character Melcu54 5 2,367 Jul-04-2021, 07:51 PM
Last Post: Melcu54
  [solved] unexpected character after line continuation character paul18fr 4 3,292 Jun-22-2021, 03:22 PM
Last Post: deanhystad
  Find string between two substrings, in a stream of data xbit 1 2,113 May-09-2021, 03:32 PM
Last Post: bowlofred
  Regular expression: cannot find 1st number in a string Pavel_47 2 2,364 Jan-15-2021, 04:39 PM
Last Post: bowlofred
  convert string into multiple columns in python3 VAN 2 2,723 Sep-26-2020, 11:14 PM
Last Post: scidam
  find a string in a field in MongoDB Leon79 2 2,371 Jul-19-2020, 09:20 PM
Last Post: menator01

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020