Python string slicing unexpected output - string

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

Related

Capitalize a character Before and After Nth character in a string in a Python list

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']

Get the nth occurrence of a letter in a string (python)

Let's say there is a string "abcd#abcd#a#"
How to get the index of the 2nd occurrence of '#' , and get the output as 9?
Since the position of the second occurrence of '#' is 9
Using a generator expression:
text = "abcd#abcd#a#"
gen = (i for i, l in enumerate(text) if l == "#")
next(gen) # skip as many as you need
4
next(gen) # get result
9
As a function:
def index_for_occurrence(text, token, occurrence):
gen = (i for i, l in enumerate(text) if l == token)
for _ in range(occurrence - 1):
next(gen)
return next(gen)
Result:
index_for_occurrence(text, "#", 2)
9
s = 'abcd#abcd#a#'
s.index('#', s.index('#')+1)

Python split string every n character

I need help finding a way to split a string every nth character, but I need it to overlap so as to get all the
An example should be clearer:
I would like to go from "BANANA" to "BA", "AN", "NA", "AN", "NA", "
Here's my code so far
import string
import re
def player1(s):
pos1 = []
inP1 = "AN"
p = str(len(inP1))
n = re.findall()
for n in range(len(s)):
if s[n] == inP1:
pos1.append(n)
points1 = len(pos1)
return points1
if __name__ == '__main__':
= "BANANA"
You can do this pretty simply with list comprehension;
input_string = "BANANA"
[input_string[i]+input_string[i+1] for i in range(0,len(input_string)-1)]
or for every nth character:
index_range = 3
[''.join([input_string[j] for j in range(i, i+index_range)]) for i in range(0,len(input_string)-index_range+1)]
This will iterate over each letter in the word banana, 0 through 6.
Then print each letter plus the next letter. Else statement for when the word reaches the last letter.
def splitFunc(word):
for i in range(0, len(word)-1):
if i < len(word):
print(word[i] + word[i+1])
else:
break
splitFunc("BANANA")
Hope this helps
Those are called n-grams.
This should work :)
text = "BANANA"
n = 2
chars = [c for c in text]
ngrams = []
for i in range(len(chars)-n + 1):
ngram = "".join(chars[i:i+n])
ngrams.append(ngram)
print(ngrams)
output: ['BA', 'AN', 'NA, 'AN', 'NA']

My for loop is not iterating through all possible values

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.

Palindrome and as well as anagrammatism?

How can we create a program that checks if the input we give(for example: EXAMPLE) has the same length and the same letters with (XAMPLEE)?
this is efficient python code for it
NO_OF_CHARS = 256
def areAnagram(str1, str2):
# Create two count arrays and initialize all values as 0
count1 = [0] * NO_OF_CHARS
count2 = [0] * NO_OF_CHARS
# For each character in input strings, increment count
# in the corresponding count array
for i in str1:
count1[ord(i)]+=1
for i in str2:
count2[ord(i)]+=1
# If both strings are of different length. Removing this
# condition will make the program fail for strings like
# "aaca" and "aca"
if len(str1) != len(str2):
return 0
# Compare count arrays
for i in xrange(NO_OF_CHARS):
if count1[i] != count2[i]:
return 0
return 1
str1 = "EXAMPLE"
str2 = "XAMPLEE"
if areAnagram(str1, str2):
print "The two strings are anagram of each other"
else:
print "The two strings are not anagram of each other"
import array
word1 = "EXAMPLE"
word2 = "XAMPLEE"
letters = array.array('i',(0,)*26)
# Count letters of word1
for c in word1:
charIndex = ord(c) - ord('A')
letters[charIndex] = letters[charIndex]+1
# Count letters of word2 and substract them from word1 count
for c in word2:
charIndex = ord(c) - ord('A')
letters[charIndex] = letters[charIndex]-1
# letters contains only 0 if words are the same
if letters.count(0) < 26:
print("Words are different")
else:
print("Words are anagrams")

Resources