Python: Finding the value of a character in a string - python

Given a long string such as:
"fkjdlfjzgjkdsheiwqueqpwnvkasdakpp"
or
"0.53489082304804918409853091868095809846545421135498495431231"
How do I find the value of the nth character in that string? I could solve this if I could convert it into a list (where each digit gets it's own index) but since the numbers aren't separated by commas I don't know how to do this either.
AFAIK there is no command like string.index(10) which would return the 11th character in.

strings are like lists. so you can access them the same way,
>>> a = "fkjdlfjzgjkdsheiwqueqpwnvkasdakpp"
>>> print a[10]
k

Strings are iterable and indexable (since it is a sequence type), so you can just use:
"fkjdlfjzgjkdsheiwqueqpwnvkasdakpp"[10]

To get the corresponding character in the nth value, just use this function:
def getchar(string, n):
return str(string)[n - 1]
Example usage:
>>> getchar('Hello World', 5)
'o'

Related

"Sorted" function doesn't work in Python task

Here's my code:
def Descending_Order(num):
return int(''.join(sorted(str(num).split(), reverse = True)))
print Descending_Order(0)
print Descending_Order(15)
print Descending_Order(123456789)
"num" is supposed to be printed in descending order, but the code doesn't work, although I don't have any errors. Any idea why it isn't being executed?
The split is superfluous, redundant and the cause of your problem. The split method of a string requires a delimiter which in your case there is none so defaults to consecutive whitespace. As your string does not have consecutive white-space, it results in a single list containing the number in string format as the only element.
>>> str('123456789').split()
['123456789']
Sorting the resultant list is invariant as what you are sorting is a list of a single element
>>> sorted(['123456789'])
['123456789']
Finally joining and converting it to an integer restores the original number
>>> int(''.join(sorted(['123456789'])))
123456789
It is worth mentioning that sorted expects a sequence, so a string would qualify enough to be sorted without splitting into individual digits
What you probably wanted is
>>> def Descending_Order(num):
return int(''.join(sorted(str(num), reverse = True)))
>>> print Descending_Order(123456789)
987654321
You can also split the numbers using list, then sort the list that way:
def Descending_Order(num):
digits = [digit for digit in list(str(num))]
return int("".join(sorted(digits, reverse = True)))
# Output
>>> Descending_Order(123456789)
987654321

Dot notation string manipulation

Is there a way to manipulate a string in Python using the following ways?
For any string that is stored in dot notation, for example:
s = "classes.students.grades"
Is there a way to change the string to the following:
"classes.students"
Basically, remove everything up to and including the last period. So "restaurants.spanish.food.salty" would become "restaurants.spanish.food".
Additionally, is there any way to identify what comes after the last period? The reason I want to do this is I want to use isDigit().
So, if it was classes.students.grades.0 could I grab the 0 somehow, so I could use an if statement with isdigit, and say if the part of the string after the last period (so 0 in this case) is a digit, remove it, otherwise, leave it.
you can use split and join together:
s = "classes.students.grades"
print '.'.join(s.split('.')[:-1])
You are splitting the string on . - it'll give you a list of strings, after that you are joining the list elements back to string separating them by .
[:-1] will pick all the elements from the list but the last one
To check what comes after the last .:
s.split('.')[-1]
Another way is to use rsplit. It works the same way as split but if you provide maxsplit parameter it'll split the string starting from the end:
rest, last = s.rsplit('.', 1)
'classes.students'
'grades'
You can also use re.sub to substitute the part after the last . with an empty string:
re.sub('\.[^.]+$', '', s)
And the last part of your question to wrap words in [] i would recommend to use format and list comprehension:
''.join("[{}]".format(e) for e in s.split('.'))
It'll give you the desired output:
[classes][students][grades]
The best way to do this is using the rsplit method and pass in the maxsplit argument.
>>> s = "classes.students.grades"
>>> before, after = s.rsplit('.', maxsplit=1) # rsplit('.', 1) in Python 2.x onwards
>>> before
'classes.students'
>>> after
'grades'
You can also use the rfind() method with normal slice operation.
To get everything before last .:
>>> s = "classes.students.grades"
>>> last_index = s.rfind('.')
>>> s[:last_index]
'classes.students'
Then everything after last .
>>> s[last_index + 1:]
'grades'
if '.' in s, s.rpartition('.') finds last dot in s,
and returns (before_last_dot, dot, after_last_dot):
s = "classes.students.grades"
s.rpartition('.')[0]
If your goal is to get rid of a final component that's just a single digit, start and end with re.sub():
s = re.sub(r"\.\d$", "", s)
This will do the job, and leave other strings alone. No need to mess with anything else.
If you do want to know about the general case (separate out the last component, no matter what it is), then use rsplit to split your string once:
>>> "hel.lo.there".rsplit(".", 1)
['hel.lo', 'there']
If there's no dot in the string you'll just get one element in your array, the entire string.
You can do it very simply with rsplit (str.rsplit([sep[, maxsplit]]) , which will return a list by breaking each element along the given separator.
You can also specify how many splits should be performed:
>>> s = "res.spa.f.sal.786423"
>>> s.rsplit('.',1)
['res.spa.f.sal', '786423']
So the final function that you describe is:
def dimimak_cool_function(s):
if '.' not in s: return s
start, end = s.rsplit('.', 1)
return start if end.isdigit() else s
>>> dimimak_cool_function("res.spa.f.sal.786423")
'res.spa.f.sal'
>>> dimimak_cool_function("res.spa.f.sal")
'res.spa.f.sal'

find last occurence of multiple characters in a string in Python

I would like to find the last occurrence of a number of characters in a string.
str.rfind() will give the index of the last occurrence of a single character in a string, but I need the index of the last occurrence of any of a number of characters. For example if I had a string:
test_string = '([2+2])-[3+4])'
I would want a function that returns the index of the last occurence of {, [, or { similar to
test_string.rfind('(', '[', '{')
Which would ideally return 8. What is the best way to do this?
max(test_string.rfind('('), test_string.rfind('['), test_string.rfind('{'))
seems clunky and not Pythonic.
You can use generator expression to do this in a Pythonic way.
max(test_string.rfind(i) for i in "([{")
This iterates through the list/tuple of characters that you want to check and uses rfind() on them, groups those values together, and then returns the maximum value.
This is pretty concise, and will do the trick.
max(map(test_string.rfind, '([{'))
You can use reversed to start at the end of the string getting the first match, using the length of the string -1 - the index i to get the index counting from the start, doing at worst a single pass over the string:
test_string = '([2+2])-[3+4])'
st = {"[", "(", "{"}
print(next((len(test_string) - 1 - i
for i, s in enumerate(reversed(test_string)) if s in st),-1))
8
If there is no match, you will get -1 as the default value. This is a lot more efficient if you a large amount of substrings to search for than doing an O(n) rfind for every substring you want to match and then getting the max of all those
>>> def last_of_many(string, findees):
... return max(string.rfind(s) for s in findees)
...
>>> test_string = '([2+2])-[3+4])'
>>> last_of_many(test_string, '([{')
8
>>> last_of_many(test_string, ['+4', '+2'])
10
>>>

Get character based on index in Python

I am fairly new to python and was wondering how do you get a character in a string based on an index number?
Say I have the string "hello" and index number 3. How do I get it to return the character in that spot, it seems that there is some built in method that I just cant seem to find.
You just need to index the string, just like you do with a list.
>>> 'hello'[3]
l
Note that Python indices (like most other languages) are zero based, so the first element is index 0, the second is index 1, etc.
For example:
>>> 'hello'[0]
h
>>> 'hello'[1]
e
its just straight forward.
str[any subscript]. //e.g. str[0], str[0][0]
Check this page...
What you need is:
Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0.
There is no separate character type; a character is simply a string of size one.
Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon.
Example:
>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'
For your case try this:
>>> s = 'hello'
>>> s[3]
'l'

Separating a string in Python

How would I separate characters once I have a string of unseparated words?
For example to translate "take the last character of the suffix and add a space to it every time ("aSuffixbSuffixcSuffix" --> "aSuffix bSuffix cSuffix").`
Or, more generally, to replace the x-nth character, where x is any integer (e.g., to replace the 3rd, 6th, 9th, etc. character some something I choose).
Assuming you're getting your string from this question, the easiest way is to not cram all the strings together in the first place. Your original create_word could be changed to this:
def create_word(suffix):
letters="abcdefghijklmnopqrstuvwxyz"
return [i + suffix for i in letters]
Then you'd be able to take e and ''.join(e) or ' '.join(e) to get the strings you want.
str = "SuffixbSuffixcSuffix"
def chunk_str(str, chunk_size):
return [str[i:i+chunk_size] for i in range(0, len(str), chunk_size)]
" ".join(chunk_str(str,3))
returns:
'Suf fix bSu ffi xcS uff ix'
You could use the replace method of strings. Check the documentation
initial = "aSuffixbSuffixcSuffix"
final = initial.replace("Suffix", "Suffix ")
print(final)

Categories