Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

How to check for string membership in python

s1 = 'perpendicular'
s2 = 'pen'
s3 = 'pep'

print(''pen' in 'perpendicular' -> {}'.format(s2 in s1))
print(''pep' in 'perpendicular' -> {}'.format(s3 in s1))


# Output

# 'pen' in 'perpendicular' -> True
# 'pep' in 'perpendicular' -> False


# If you are more interested in finding the location of a substring within a string
# (as opposed to simply checking whether or not the substring is contained),
# the find() string method can be more helpful.

s = 'Does this string contain a substring?'

print(''string' location -> {}'.format(s.find('string')))
print(''spring' location -> {}'.format(s.find('spring')))


# Output

# 'string' location -> 10
# 'spring' location -> -1


# find() returns the index of the first character of the first occurrence of the substring by default,
# and returns -1 if the substring is not found
Source by www.kdnuggets.com #
 
PREVIOUS NEXT
Tagged: #How #check #string #membership #python
ADD COMMENT
Topic
Name
7+3 =