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'
Related
I have this string here '[2,3,1,1,]'
Im new to slicing and I only know how to slice from the start and from the end but not somewhere between, not even sure if that is possible.
could someone tell me how I can slice this '[2,3,1,1,]' to this '[2,3,1,1]'
So removing the second last character only.
If you just want to delete the second last character, your can do like this,
s = "[2,3,1,1,]"
s[:-2] + s[-1]
# '[2,3,1,1]'
s[:-2] -> Will slice the string from 0 to -2 index location (without -2 index)
s[-1] -> Will fetch the last element
s[:-2] + s[-1] -> concatenation of the strigs
If you're sure you have that string, slice both characters and add the ] back on!
source_string = "[2,3,1,1,]"
if source_string.endswith(",]"):
source_string = source_string[:-2] + "]"
However, often lists stored as strings are not very useful - you may really want to convert the whole thing to a collection of numbers (perhaps manually removing the "[]" and splitting by ,, or using ast.literal_eval()), potentially converting it back to a string to display later
>>> source_string = "[2,3,1,1,]"
>>> import ast
>>> my_list = ast.literal_eval(source_string)
>>> my_list
[2, 3, 1, 1]
>>> str(my_list)
'[2, 3, 1, 1]'
You can use this for this one case
txt = "[2,3,1,1,]"
print(f"{txt[:-2]}{txt[-1]}")
Even tho storing lists as string is a bit weird
txt[:-2] will get the characters from 0 index to -2 index
txt[-1] will get the last character which is "]"
then I concatenate both with an f"" string
You can use this if you don't wanna use an f string
print(txt[:-2], txt[-1], sep="")
the "sep" argument is so there won't be space between the two prints
Using built-in functions such as str.rstrip
l = '[2,3,1,1,]'
l_new = f"{l.rstrip('],')}]" # it doesn't matter the order!
print(l_new)
or str.rpartition
a, _, b = l.rpartition(',')
l_new = a + b
print(l_new)
you can avoid an explicit slicing. See doc for details.
The 1st approach is universal, hence doesn't produce any side-effects. The 2nd may give rise to side-effects if the final last character is not a ,. If necessary use a check, i.e. str.endswith, to fix it.
I want to find the index of two substrings in a string of characters given like this:
find_start = '1L'
find_end = 'L'
>>> blah = 'A1LELST5W'
>>> blah.index('1L')
1
>>> blah.index('L')
2 # i want it to give me 4
If I use the index method, it gives me the "L" that's the third character in the string. But I want it to treat "1L" and "L" as separate strings and give me the fifth character instead.
Is there a simple way of doing this? Or would I have to store everything except find_start in a new string and then try to index through that? (But that would mess with the position of everything inside the string).
The str.index method has start and end arguments that allow you to constrain the search. So you just need to start the second search where the first one ends:
>>> find_start = '1L'
>>> find_end = 'L'
>>> blah = 'A1LELST5W'
>>> first = blah.index('1L')
>>> first
1
>>> blah.index('L', first + len(find_start))
4
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'
If I am building a basic encryption program in python that reassigns A to C and D to F and so on, what is a simple algorithm I could use to do this?
I have a list named alphabet that holds each letter, then a variable that takes in the user input to change to the encrypted version.
str.translate should be the easiest way:
table = str.maketrans(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"cdefghijklmnopqrstuvwxyzabCDEFGHIJKLMNOPQRSTUVWXYZAB"
)
s = "Test String"
print(s.translate(table))
Output:
Vguv Uvtkpi
There's two major parts to this. First, ciphering a single letter; and second, applying that to the whole string. We'll start with the first one.
You said you had a list with the alphabet in it. Suppose, too, that we have a letter.
>>> letter = 'F'
If we want to replace that letter with the letter two spaces down in the alphabet, first we'll probably want to find the numerical value of that letter. To do that, use index:
>>> alphabet.index(letter)
5
Next, you can add the offset to it and access it in the list again:
>>> alphabet[alphabet.index(letter) + 2]
'H'
But wait, this won't work if we try doing a letter like Z, because when we add the index, we'll go off the end of the list and get an error. So we'll wrap the value around before getting the new letter:
>>> alphabet[(alphabet.index('Z') + 2) % len(alphabet)]
'B'
So now we know how to change a single letter. Python makes it easy to apply it to the whole string. First putting our single-letter version into a function:
>>> def cipher_letter(letter):
... return alphabet[(alphabet.index(letter) + 2) % len(alphabet)]
...
We can use map to apply it over a sequence. Then we get an iterable of ciphered characters, which we can join back into a string.
>>> ''.join(map(cipher_letter, 'HELLOWORLD'))
'JGNNQYQTNF'
If you want to leave characters not in alphabet in place, add a test in cipher_letter to make sure that letter in alphabet first, and if not, just return letter. VoilĂ .
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'