Python Forum
Strings containing both symbols and letters
Thread Rating:
  • 2 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Strings containing both symbols and letters
#6
There are multiple ways how to check it. Some examples:

You can for each symbol test whether its in a string and stop when you found one or everything is tested:
Output:
In [32]: symbols = "!@#$%^&*()_+"     ...: test_string = "string with $ symbol"     ...:     ...: contains_symbol = False     ...: for symbol in symbols:     ...:     if symbol in test_string:     ...:         contains_symbol = True     ...:         break     ...: print(contains_symbol)     ...: True
Last code could be rewritten as a list comprehension or generator expression:
Output:
In [33]: contains_symbol = any(symbol in test_string for symbol in symbols)     ...: print(contains_symbol)     ...: True
You can convert both test_string and symbols to sets and check their intersection:
Output:
In [34]: common_symbols = set(symbols) & set(test_string)     ...: print(common_symbols)     ...: contains_symbol = bool(common_symbols)     ...: print(contains_symbol)     ...: {'$'} True
You can import re and use regular expression to search for occurence:
Output:
In [38]: import re     ...: re.search("[!@#$%^&*\(\)_+]", test_string)     ...: Out[38]: <_sre.SRE_Match object; span=(12, 13), match='$'>
To check if string contains text character you would do exactly same but instead of symbols string you would use string consisting of your "text" characters. Its possbile to check both symbols and text with one regular expression, but matching pattern for that will be little more complicated.
Reply


Messages In This Thread
RE: Strings containing both symbols and letters - by zivoni - Apr-04-2017, 08:50 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python script that deletes symbols in plain text nzcan 3 726 Sep-05-2023, 04:03 PM
Last Post: deanhystad
  Trying to understand strings and lists of strings Konstantin23 2 842 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  Splitting strings in list of strings jesse68 3 1,839 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  cyrillic symbols in tables in reportlab. hiroz 5 11,662 Sep-10-2020, 04:57 AM
Last Post: bradmalcom
  Unexpected output: symbols for derivative not being displayed saucerdesigner 0 2,091 Jun-22-2020, 10:06 PM
Last Post: saucerdesigner
  Replacing symbols by " Tiihu 1 1,917 Feb-13-2020, 09:27 PM
Last Post: Larz60+
  How do I delete symbols in a list of strings? Than999 1 2,326 Nov-16-2019, 09:37 PM
Last Post: ibreeden
  Finding multiple strings between the two same strings Slither 1 2,568 Jun-05-2019, 09:02 PM
Last Post: Yoriz
  lists, strings, and byte strings Skaperen 2 4,284 Mar-02-2018, 02:12 AM
Last Post: Skaperen
  Python symbols AND letters gullidog 1 3,530 Apr-05-2017, 10:13 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

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