I am very beginner in Python.
aString = 'fruit list is: <carrot>, <orange>, <pineapple>, <grape>, <watermelon>, <mangosteen>'
From my aString, sometime I need a string 'carrot'; sometime I need a string 'watermelon'; sometime I need a string 'mangosteen'.
Does Python have a function to get string between two character with specific index?
I am very thankful if somebody can help to solve this problem.
you can get a substring between two indexes like this
aString[start: end]
where start and end are integers
It's too late but that's my own function:
def Between(first, second, position, string, direction='forward'):
# if you have the index of the second character you can use it but add direction = 'back' or anything except 'forward'
result = ""
pairs = 1
if direction == 'forward':
for i in string[position+1:]:
if i == first: pairs += 1
elif i == second: pairs -= 1
if pairs==0: break
result = result+i
else:
for i in (string[:position])[::-1]:
if i == second: pairs += 1
elif i == first: pairs -= 1
if pairs==0: break
result = i+result
return result
# for example:
string = "abc(defg)hijklmenop"
print(Between("(", ")", 3, string)) # direction = 'forward'
print(Between("(", ")", 8, string, direction='back'))
# Also it works in this case:
string = "abcd(efg(hij)klmno)pqrstuvwxyz"
print(Between("(", ")", 4, string)) # direction = 'forward'
print(Between("(", ")", 18, string, direction='back'))
Related
So let's say I have a string, like this:
string = '12345+67890'
I want to go back to search for that plus, and add a letter 'H', so the end result would be like this:
string = '12345+h67890
Also, what if I want to get the latest +, so if there is two +'s, I want to get the last +?
Any help would be appreciated!
You could use reverse split to split on the last instance of +, then join with +H:
>>> '+H'.join('123+456+789'.rsplit('+',1))
'123+456+H789'
Convert into list, iterate through list, when you find the plus add an 'h' into the next index.
string = '12345+67890'
stringList = list(string)
i = 0
newString = ''
for i in range(len(stringList)):
if stringList[i] == '+':
stringList.insert(i+1,'h')
for letter in stringList:
newString += letter
print(newString)
Since you asked how to do it with if statements:
i = -1
for i in range(len(my_str)):
if my_str[i] == '+':
plus = i+1 # <- will update every time you see a + symbol
if i != -1:
my_str = my_str[:i] + 'h' + my_str[i:]
Alternatively, you can search backwards:
i = -1
for i in reversed(range(len(my_str))):
if my_str[i] == '+':
plus = i+1 # <- will update every time you see a + symbol
break
if i != -1:
my_str = my_str[:i] + 'h' + my_str[i:]
As others have mentioned you can use built-in functions like find and rfind. My personal choice is to refer to regular expressions for this type of thing:
import re
my_str = re.sub('(.*\+)(.*)',r"\1h\2", my_str))
I am able to iterate through two given strings of the same length.
I am supposed to output a green emoji if the letters in guess_word are are also contained and in the correct position of the secret_word. If a letter in the guess_word is in the secret_word but it's in the wrong position, then I should have an output of a yellow emoji.
This is where my issue is. The yellow emoji is not showing up in my output, only the green and white boxes. I have a picture below of what it should look like in the output.
I have to stick to two different functions because this is what my homework is asking me to do.
def contains_char(any_length: str, single_character: str) -> bool:
"""Loop iterates through each character in string to find matching character."""
assert len(single_character) == 1
if single_character in any_length:
return True
else:
return False
def emojified(guess_word: str, secret_word: str) -> str:
"""A way to match letters to its corresponding emoji color output. """
assert len(guess_word) == len(secret_word)
WHITE_BOX: str = "\U00002B1C"
GREEN_BOX: str = "\U0001F7E9"
YELLOW_BOX: str = "\U0001F7E8"
emoji_color: str = ""
i: int = 0
while i < len(secret_word):
i += 1
if guess_word[0] in secret_word[0]:
emoji_color += GREEN_BOX
i += 1
else:
emoji_color += WHITE_BOX
i += 1
if contains_char is True:
emoji_color += YELLOW_BOX
else:
emoji_color += WHITE_BOX
return emoji_color
Output:
Without changing too much, here's how I would write your while-loop:
while i < len(secret_word):
guess_char = guess_word[i]
secret_char = secret_word[i]
current_emoji = WHITE_BOX # By default, we display a white box for this position
if contains_char(secret_word, guess_char):
current_emoji = YELLOW_BOX # guess_char is in secret_word. guess_char may even be in the correct position, but we don't care about that yet.
if guess_char == secret_char:
current_emoji = GREEN_BOX # guess_char is in the correct position.
emoji_color += current_emoji
i += 1
return emoji_color
In order to properly process the "same-position" matches without interfering with the "different-position" matched, you need to check for same-positions first and fallback on diffrent-position matches otherwise.
You can do this by replacing characters in a comprehension that you join into the final result.
For example:
def emojified(guess,secret):
WHITE_BOX = "\U00002B1C"
GREEN_BOX = "\U0001F7E9"
YELLOW_BOX = "\U0001F7E8"
return "".join( GREEN_BOX if s==g # same-position
else YELLOW_BOX if g in secret # different-position
else WHITE_BOX # no match
for s,g in zip(secret,guess)) # character pairs
Output:
print(emojified("hello","world")) # ⬜️⬜️🟨🟩🟨
print(emojified("elloh","hello")) # 🟨🟨🟩🟨🟨
print(emojified("python","woohoo")) # ⬜️⬜️⬜️🟩🟩⬜️
print(emojified("python","python")) # 🟩🟩🟩🟩🟩🟩
print(emojified("yikyak","tiktok")) # ⬜️🟩🟩⬜️⬜️🟩
This question already has answers here:
Return middle part of string
(2 answers)
Closed 1 year ago.
Full problem:
Write a function named mid that takes a string as its parameter. Your function should extract and return the middle letter. If there is no middle letter, your function should return the empty string. For example, mid("abc") should return "b" and mid("aaaa") should return "".
Question:
How come at the very end print(x) and everything works as expected, but return x breaks the program with the following:
IndexError: list index out of range
import math
def mid(string):
enum = list(enumerate(string))
lastnum = enum[-1][0] + 1
if lastnum % 2 == 0:
return ""
else:
middle = math.floor(len(enum)/2)
x = enum[middle][1]
print(x)
return x
mid("asaba")
Here's an example of how I would approach it:
def mid(string):
if len(string) % 2 == 0:
return ""
else:
offset = int(len(string) / 2)
return string[offset: offset + 1]
mid("abc")
mid("asaba")
Your code fails on edge cases, specifically when given the empty string, but I found during my tests that it works for strings like "asaba", "aaaa", and "abc" but throws the error when given "". The reason for this is because lastnum = enum[-1][0] + 1 will give an index that does not exist for the empty string. The way to fix this would be to add a condition at the beginning of your function that checks if it's an empty string, so like this:
if len(string) == 0:
return ""
import math
def mid(string_1):
string_2 = ''
if len(string_1) %2 == 0:
return string_2
else:
string_2 = string_1[math.floor(len(string_1)/2)]
return string_2
print(mid("abc"))
I've done the function in this way and it works fine, the logic is the following:
If the length of the string is even return an empty string ""
If the length of the string is odd then returns the middle character, this is done by finding the index in the middle:
string_2 = string_1[math.floor(len(string_1)/2)]
I'd like write code to find specific instances of words in a long string of text, where the letters making up the word are not adjacent, but consecutive.
The string I use will be thousands of characters long, but a as a shorter example... If I want to find instances of the word "chair" within the following string, where each letter is no more than 10 characters from the previous.
djecskjwidhl;asdjakimcoperkldrlkadkj
To avoid the problem of finding many instances in a large string, I'd prefer to limit the distance between every two letters to 10. So the word chair in the string abcCabcabcHabcAabdIabcR would count. But the word chair in the string abcCabcabcabcabcabcabcabcabHjdkeAlcndInadhR would not count.
Can I do this with python code? If so I'd appreciate an example that I could work with.
Maybe paste the string of text or use an input file? Have it search for the word or words I want, and then identify if those words are there?
Thanks.
This code below will do what you want:
will_find = "aaaaaaaaaaaaaaaaaaaaaaaabcCabcabcHabcAabdIabcR"
wont_find = "abcCabcabcabcabcabcabcabcabHjdkeAlcndInadhR"
looking_for = "CHAIR"
max_look = 10
def find_word(characters, word):
i = characters.find(word[0])
if i == -1:
print("I couldnt find the first character ...")
return False
for symbol in word:
print(characters[i:i + max_look+1])
if symbol in characters[i:i + max_look+1]:
i += characters[i: i + max_look+1].find(symbol)
print("{} is in the range of {} [{}]".format(symbol, characters[i:i+ max_look], i))
continue
else:
print("Couldnt find {} in {}".format(symbol, characters[i: i + max_look]))
return False
return True
find_word(will_find, looking_for)
print("--------")
find_word(wont_find, looking_for)
An alternative, this may also work for you.
long_string = 'djecskjwidhl;asdjakimcoperkldrlkadkj'
check_word = 'chair'
def substringChecker(longString, substring):
starting_index = []
n , derived_word = 0, substring[0]
for i, char in enumerate(longString[:-11]):
if char == substring[n] and substring[n + 1] in longString[i : i + 11]:
n += 1
derived_word += substring[n]
starting_index.append(i)
if len(derived_word) == len(substring):
return derived_word == substring, starting_index[0]
return False
print(substringChecker(long_string, check_word))
(True, 3)
To check if the word is there:
string = "abccabcabchabcaabdiabcr"
word = "chair"
while string or word:
index = string[:10].find(word[0])
if index > -1:
string = string[index+1:]
word = word[1:]
continue
if not word:
print("found")
else:
break
I have a function that decrements a whole number parameter represented by a string. For instance, if I pass in the string "100", it should return "99."
def dec(s):
i = len(s) - 1
myString = ""
while (i >= 0):
if s[i] == '0':
s[i] = '9'
i -= 1
else:
s[i] = chr(int(s[i]) - 1)
break
return s
However, Python issues this error.
s[i] = '9'
TypeError: 'str' object does not support item assignment
I am assuming that s[i] cannot be treated as an lvalue. What is a solution around this?
You can do:
s = s[:i] + "9" + s[i+1:]
This takes the part of the string before character index i, appends a 9, then appends the part of the string after character index i. However, doing a lot of string appends like this is not terribly efficient.
The other answer is that if you're dealing with numbers, why not actually use numbers instead of strings?
def dec(s):
return str(int(s) - 1)
Strings aren't mutable, but lists are. You can easily convert the string to a list of individual characters:
l = list(s)
Then convert it back:
s = ''.join(l)
Since you're working with a numeric string there are more direct approaches, but this answer works for the general case.
You can't. In Python, strings are immutable -- once created, they can't be changed.
You have two options without changing your function entirely.
Convert the string to a list and back:
def dec(s):
s = list(s)
i = len(s) - 1
myString = ""
while (i >= 0):
if s[i] == '0':
s[i] = '9'
i -= 1
else:
s[i] = chr(int(s[i]) - 1)
break
return ''.join(s)
Create a new string each time you want to make a change:
def dec(s):
i = len(s) - 1
myString = ""
while (i >= 0):
if s[i] == '0':
s = s[:i] + "9" + s[i+1:]
i -= 1
else:
s = s[:i] + chr(int(s[i]) - 1) + s[i+1:]
break
return s
I'm not sure why you are playing with the string character by character. Isn't this simpler?
def decrement_string(s):
try:
i = int(s)
i = i - 1
return str(i)
except:
# do something else
return "that's no number!"
while True:
s = raw_input("give me a number and I'll decrement it for you: ")
print decrement_string(s)
The solution to your specific problem of "decrementing" strings is to convert s to an int with int(s), decrease that, and convert back to a str: str(int(s)-1).
In [175]: str(int('100')-1)
Out[175]: '99'
The general solution is to not attempt to alter the elements of a string; use some other type to represent your work, and convert to a string as the last step.
Python strings are immutable so you cannot modify them. You have to create a new string that contains the value that you need. You are better off converting the string to an integer, decrementing it, and then converting it back to an integer again.
The reason for immutable strings is primarily efficiency.