What is the Python 3 equivalent of find ()? - python

I'm working on the MIT open courseware for python but have having a hard time with the following example:
To get started, we are going to use some built-in Python functions. To use these functions, include the statement
from string import *
at the beginning of your file. This will allow you to use Python string functions. In particular, if you want to find the starting point of the first match of a keyword string key in a target string target you could use thefind function.
Try running on some examples, such as find("atgacatgcacaagtatgcat","atgc")
Note how it returns the index of the first instance of the key in the target. Also note that if no instance of the key exists in the target, e.g, find("atgacatgcacaagtatgcat","ggcc") it returns the value -1.
The course in python 2.4 (or so) but I'm trying to do the assignments in Py3.. learning the differences along the way.

Use the .find() method of a string, rather than string.find(). (This also works, and is probably preferable, in python 2).

Isn't it still just find? From the documentation:
str.find(sub[, start[, end]])
Return the lowest index in the string
where substring sub is found, such
that sub is contained in the slice
s[start:end]. Optional arguments start
and end are interpreted as in slice
notation. Return -1 if sub is not
found.

str = "Python"
In Python2:
string.find(str,"y")
In Python3:
str.find("y")

For Python2 and Python3:
if 'atgc' in 'atgacatgcacaagtatgcat':
#do something

name = "ALIEN" # complete String
letter = 'E' # substring
#string.find(substring[start:end])
name.find(letter[:])
Output : 3

Related

Same value returned when using find and rfind on a string in Python 3.7.0 (using idle)

Novice user of Python and Stack Overflow - first question
I am perplexed of why I am getting same value for find and rfind (Python 3.7.0) for the following:
>>> string="ooook"
>>> string.rfind('k')
4
>>> string.find('k')
4
One of these should be 0, shouldn't it?
-Has rfind changed in later versions of Python?
-Am I supposed to import something to use find and rfind?
-Local issue with my PC?
If you are using ipython (I can warmly recommend) you can type ?? before a command in order to see its docstring.
Doing so for string.rfind:
Docstring:
S.rfind(sub[, start[, end]]) -> int
Return the highest 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.
Type: builtin_function_or_method
and for string.find:
Docstring:
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.
Type: builtin_function_or_method
I took the liberty to highlight the important parts.
What it means is that both will return the same index if there is only one substring (i.e. 'k' in your case) found.
If you are still unsure about how str.rfind and str.find differ from each other, try the same thing with:
string = 'kooook'
Hope that helps and happy coding!
As far as I know, rfind() do the same as find(), but return the last index.
Being only one 'k', the two of the return the same.
With 'o', the result will be different.

Python 3.x: Find if substring is at the end of a string w/o using endswith()

I have created a program to check if a string is a substring of another string, with the added condition of that substring being at the end.
def atEnd(first, second):
if second in first and first.endswith(second):
return True
else:
return False
first, second = input('Enter two strings: ').split()
print(atEnd(first, second))
Is there a way to find the same outcome without using the .endswith() function?
first[-len(second):] == second
Will do the job.
Your atEnd function is completely redundant with str.endswith, which is a built-in native method and therefore will already have a highly efficient implementation.
I would simply write print(first.endswith(second)) -- there's no need to complicate things further.
If you really want a free function rather than a method for some reason, then you can just invoke str.endswith directly: print(str.endswith(first, second)).
If you want to write your own implementation for efficiency reasons, you'll probably be better off using an alternative algorithm (e.g. building a suffix tree). If you want to write your own implementation to understand low-level string operations you really should learn C and read the CPython implementation source code. If you are doing this because a school assignment told you not to use endswith then that seems like a dumb assignment to me -- you should probably ask your teacher for more information.
Try utilizing re module's method findall:
import re
EndsWith = lambda first,second: re.findall("("+first+")$",second) != []

Simulate normalizing arguments

If you pass string like this to your python as program argument
my.py name1=abc name2='def' name3="ghi klm"
then sys.args will return list like this
['name1=abc', 'name2=def', 'name3=ghi klm']
thus all quotes are considered and removed. Which function in python can take string of arguments and return such normalized list?
Update
Input string -> 'name1=abc name2=\'def\' name3="ghi klm"'
Output list -> ['name1=abc', 'name2=def', 'name3=ghi klm']
To split arguments in the same way as the shell, you can use shlex.split():
>>> shlex.split("name1=abc name2='def' name3=\"ghi klm\"")
['name1=abc', 'name2=def', 'name3=ghi klm']
Which function in python can take string of arguments and return such normalized list?
There may be one, but the work is actually done by your operating system. The Python interpreter just propagates the list it gets from the OS as sys.args.

Python, string (consisting of variable and strings, concatenated) used as new variable name?

I've been searching on this but am coming up a little short on exactly how to do specifically what i am trying to do.. I want to concatentate a string (I guess it would be a string in this case as it has a variable and string) such as below, where I need to use a variable consisting of a string to call a listname that has an index (from another variable).. I simplified my code below to just show the relevant parts its part of a macro that is replacing values:
toreplacetype = 'type'
toreplace_indx = 5
replacement_string = 'list'+toreplacetype[toreplace_indx]
so... I am trying to make the string on the last line equal to the actual variable name:
replacement_string = listtype[5]
Any advice on how to do this is appreciated
EDIT:
To explain further, this is for a macro that is sort of a template system where I am indicating things in a python script that I want to replace with specific values so I am using regex to do this. So, when I match something, I want to be able to replace it from a specific value within a list, but, for example, in the template I have {{type}}, so I extract this, but then I need to manipulate it as above so that I can use the extracted value "type" to call a specific value from within a list (such as from a list called "listtype") (there is more than 1 list so I need to find the one called "listtype" so I just want to concatenate as above to get this, based on the value I extracted using regex
This is not recommended. Use a dict instead.
vars['list%s' % toreplacetype][5] = ...
Hrm...
globals()['list%s'% toreplacetype][toreplace_indx]
replacement_string = 'list'+toreplacetype+'['+str(toreplace_indx)+']'
will yield listtype[5] when you print it.
You need to basically break it into 5 parts: 1 string variable, 3 strings and an int casted to a string.
I think this is what you are asking?

What's the Ruby equivalent of Python's output[:-1]?

In Python, if I want to get the first n characters of a string minus the last character, I do:
output = 'stackoverflow'
print output[:-1]
What's the Ruby equivalent?
I don't want to get too nitpicky, but if you want to be more like Python's approach, rather than doing "StackOverflow"[0..-2] you can do "StackOverflow"[0...-1] for the same result.
In Ruby, a range with 3 dots excludes the right argument, where a range with two dots includes it. So, in the case of string slicing, the three dots is a bit more close to Python's syntax.
Your current Ruby doesn't do what you describe: it cuts off the last character, but it also reverses the string.
The closest equivalent to the Python snippet would be
output = 'stackoverflow'
puts output[0...-1]
You originally used .. instead of ... (which would work if you did output[0..-2]); the former being closed–closed the latter being closed–open. Slices—and most everything else—in Python are closed–open.
"stackoverflow"[0..-2] will return "stackoverflo"
If all you want to do is remove the last character of the string, you can use the 'chop' method as well:
puts output.chop
or
puts output.chop!
If you only want to remove the last character, you can also do
output.chop

Categories

Resources