I'm trying to store substrings of letters in 's' that are in alphabetical order in a list
s = 'azcbobobegghakl'
string = ''
List = []
i = -1
for letter in s:
if letter == s[0]:
string += letter
elif letter >= s[i]:
string += letter
elif letter < s[i]:
List.append(string)
string = letter
i += 1
print(List)
My expected result:
['az', 'c', 'bo', 'bo', 'beggh', 'akl']
And my actual Output:
['az', 'c', 'bo', 'bo']
Firstly, your first if statement is incorrect. It should be if i == -1:. Because of this bug, you are ignoring the second a character in s.
Secondly, at the end of the string you don't add what's left of string into List.
As such, the following is what you want:
s = 'azcbobobegghakl'
string = ''
List = []
i = -1
for letter in s:
if i == -1:
string += letter
elif letter >= s[i]:
string += letter
elif letter < s[i]:
List.append(string)
string = letter
i += 1
List.append(string)
print(List)
An example is available here.
Related
Here is my code I am trying uppercase letters before and after a specific letter in a list. Uppercase any letter before and after
uppercase the previous and next letters that come before and after each "z" in a capital city. All other letters are lowercase. All cities that contain that letter will be stored in a list and returned. If I could get some input that would be great. Also if I need to change the code completely please let me know of other ways. I am new to this any input would be appreciated. Thanks
lst = ['brazzaville', 'zagreb', 'vaduz']
lst2 = []
for wrd in lst:
newwrd = ''
for ltr in wrd:
if ltr in 'ua':
newwrd += ltr.capitalize()
else:
newwrd += ltr
lst2.append(newwrd)
print(lst2)
I keep getting this:
['brAzzAville', 'zAgreb', 'vAdUz']
But I need this:
['brAzzAville', 'zAgreb', 'vadUz']
The following strategy consists of iterating through the word and replacing the letters at index-1 and index+1 of z (if they exist) with upper case letters:
lst2 = []
for wrd in lst:
wrd = wrd.lower()
for idx, letter in enumerate(wrd):
if letter == 'z':
if idx-1 > 0 and wrd[idx - 1] != 'z':
wrd = wrd.replace(wrd[idx - 1], wrd[idx - 1].upper())
if idx+1 < len(wrd) and wrd[idx + 1] != 'z':
wrd = wrd.replace(wrd[idx + 1], wrd[idx + 1].upper())
if "z" in wrd:
lst2.append(wrd)
print(lst2)
#['brAzzAville', 'zAgreb', 'vadUz']
I think this code gives correct answer , verify once
def findOccurrences(s, ch):
return [i for i, letter in enumerate(s) if letter == ch]
lst = ['brazzaville', 'zagreb', 'vaduz']
lst2 = []
result = []
for wrd in lst:
newwrd = ''
result = findOccurrences(wrd, 'z')
for i in range(len(wrd)):
if (i + 1 in result or i - 1 in result) and wrd[i] != 'z':
newwrd += wrd[i].capitalize()
else:
newwrd += wrd[i]
lst2.append(newwrd)
print(lst2)
Capitalize Nth character in a string
res = lambda test_str,N: test_str[:N] + test_str[N].upper() + test_str[N + 1:] if test_str else ''
Pseudocode
Loop through the list and filter the list for strings that contain 'z'.
[check(i) for i in lst if 'z' in i]
For each item in the list:
find the index and capitalize the preceding character to the first occurence of 'z' without rotation.
preind = list(i).index('z')-1 if list(i).index('z')-1>0 else None
k = res(stri,preind) if(preind) else i
find the index and capitalize the succeeding character to the last occurence of 'z' without rotation.
postind = i.rfind('z')+1 if i.rfind('z')+1<len(i) else None
stri = res(i,preind) if(preind) else stri
Code
lst = ['brazzaville', 'zagreb', 'vaduz']
def check(i):
stri = ""
k = ""
i = i.lower()
# lambda expression to capitalise Nth character in a string
res = lambda test_str,N: test_str[:N] + test_str[N].upper() + test_str[N + 1:] if test_str else ''
# find index of the preceeding character to 'z'
preind = list(i).index('z')-1 if list(i).index('z')-1>0 else None
# find index of the succeeding character to 'z'
postind = i.rfind('z')+1 if i.rfind('z')+1<len(i) else None
# capitalise preceeding character to 'z'
stri = res(i,preind) if(preind) else i
# capitalise succeeding character to 'z'
k = res(stri,postind) if(postind) else stri
# return the processed string
return k
print([check(i) for i in lst if 'z' in i ])
#output
['brAzzAville', 'zAgreb', 'vadUz']
How to delete the vowel from the given string?
letter = 'raeiou'
new_string = []
for i in letter:
new_string.append(i)
for j in new_string:
if j == 'a' or j == 'e' or j == 'i' or j == 'o' or j == 'u':
new_string.remove(j)
final = ''.join(new_string)
print('The string after removing the vowels is {}'.format(final))
expected output r but reo
When you do:
for j in new_string:
...
new_string.remove(...)
you are modifying a list while looping on it (see e.g. strange result when removing item from a list).
You could simply skip vowels when you create new_list in the first place:
for i in letter:
if not i in 'aeiou':
new_string.append(i)
final = ''.join(new_string)
Here is an alternative suggestion:
def func(s):
for c in 'aeiouAEIOU':
s = ''.join(s.split(c))
return s
You don't need two loops for this!
letter = 'raeiou'
new_string = letter
vowels = ('a', 'e', 'i', 'o', 'u')
for i in letter:
if i in vowels:
new_string = new_string.replace(i,"");
print('The string after removing the vowels is {}'.format(new_string))
I want to split my string using python 3+ which is having commas. I don't want string to split based on commas inside brackets.
For example:-
cstr = 'animal_tiger,(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))'
I want to split this into two string elements.
I tried splitting based on commas but it is taking inside commas as well.
import re
import csv
from StringIO import StringIO
cstr = 'animal_tiger,(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))'
b = re.split(r',(?=")', cstr)
print(b)
c = re.split(''',(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', cstr)
print(c)
data = StringIO(cstr)
reader = csv.reader(data, delimiter=';')
for row in reader:
print(row)
def split_with_commas_outside_of_quotes(string):
arr = []
start, flag = 0, False
for pos, x in enumerate(string):
if x == '(' and x == ')':
flag= not(flag)
if flag == False and x == ',':
arr.append(string[start:pos])
start = pos+1
arr.append(string[start:pos])
return arr
print(split_with_commas_outside_of_quotes(cstr))
print(cstr.replace('(','$')).replace(')','#').split(',')
Expected result is splitting of string into two different strings of list that is:-
outputlist - ['animal_tiger','(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))']
remember the length of the list is 2.
Here you go. Use this function:
def split_with_commas_outside_of_quotes(string):
arr = []
bracketCount = 0
currentItem = ""
for i in range(len(string)):
if i == len(string)-1:
currentItem += string[i]
arr.append(currentItem)
elif string[i] == "(":
bracketCount += 1
currentItem += string[i]
elif string[i] == ")":
bracketCount -= 1
currentItem += string[i]
elif bracketCount == 0 and string[i] == ",":
arr.append(currentItem)
currentItem = ""
else:
currentItem += string[i]
return arr
cstr = 'animal_tiger,(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))'
print(split_with_commas_outside_of_quotes(cstr))
Output:
['animal_tiger', '(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",)),1,3) AS INT))']
You can use split():
data = """animal_tiger,(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",'')),1,3) AS INT))"""
data.split(',', 1)
>>> ['animal_tiger',
'(CAST(SUBSTR(TRIM(replace(MAX(tigers_name),"Body Parts",\'\')),1,3) AS INT))']
VOWELS = ['a', 'e', 'i', 'o', 'u']
BEGINNING = ["th", "st", "qu", "pl", "tr"]
def pig_latin2(word):
# word is a string to convert to pig-latin
string = word
string = string.lower()
# get first letter in string
test = string[0]
if test not in VOWELS:
# remove first letter from string skip index 0
string = string[1:] + string[0]
# add characters to string
string = string + "ay"
if test in VOWELS:
string = string + "hay"
print(string)
def pig_latin(word):
string = word
transfer_word = word
string.lower()
test = string[0] + string[1]
if test not in BEGINNING:
pig_latin2(transfer_word)
if test in BEGINNING:
string = string[2:] + string[0] + string[1] + "ay"
print(string)
When I un-comment the code below and replace print(string) with return string in above two functions, it only works for words in pig_latin(). As soon as word should be passed to pig_latin2() I get a value of None for all words and the programs crashes.
# def start_program():
# print("Would you like to convert words or sentence into pig latin?")
# answer = input("(y/n) >>>")
# print("Only have words with spaces, no punctuation marks!")
# word_list = ""
# if answer == "y":
# words = input("Provide words or sentence here: \n>>>")
# new_words = words.split()
# for word in new_words:
# word = pig_latin(word)
# word_list = word_list + " " + word
# print(word_list)
# elif answer == "n":
# print("Goodbye")
# quit()
# start_program()
You're not capturing the return value of the pig_latin2 function. So whatever that function does, you're discarding its output.
Fix this line in the pig_latin function:
if test not in BEGINNING:
string = pig_latin2(transfer_word) # <----------- forgot 'string =' here
When fixed thusly, it works for me. Having said that, there would still be a bunch of stuff to clean up.
I am currently facing a weird issue with string slicing. I cannot understand a part of the code below.
s = 'azcbobobegghakl'
curString = s[0]
longest = s[0]
for i in range(1, len(s)):
if s[i] >= curString[-1]:
curString += s[i]
if len(curString) > len(longest):
longest = curString
else:
curString = s[i]
print 'Longest substring in alphabetical order is:', longest
In particular, the part where curString[-1] is. I was trying to determine what is the point of curString[-1] in that code.
I made this test:
>>> s = 'azcbobobegghakl'
>>> curString = s[0]
>>> curString
'a'
>>> curString[-1]
'a'
When defining a new variable with the same string and trying the same [-1] slicing , it returns the first letter of the string, whereas I expected it to return the last (due to the [-1] but it does not. Why is that ?
This statment:
>>> s = 'azcbobobegghakl'
>>> curString = s[0]
will assign the value of "a" to curString. s[0] is just the first element of the string s, it is not a range or a slice of the string s.
The problem is(I think) you are slicing the wrong list
>>> s = 'azcbobobegghakl'
>>> curString = s[0]
>>> print(curString)
a
Here curString is equal to "a"
So curString[-1] = "a" since the last character of curString is "a"
If you want the last character of 'azcbobobegghakl' do:
>>> curString = s[-1] # This is "l"
>>> print(curString)
l