A function similar to split() [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I was wondering what the A != "" does in this code.
def mysplit(strng):
A = ""
B = []
for i in strng:
if i != " ":
A += i
elif A != "":
B.append(A)
A = ""
# Append last word
if A != "":
B.append(A)
return(B)
This is the code that I found for a uni project that i need, but that piece of code doesn't make sense to me, isnt it just empty? how are you gonna get an empty character in your text apart from the spaces?
also, do strings have positions?

Explanation:
What this function will do is accept a string as an argument, and then loop through each character of the string.
The first if will add character by character to A until it reaches a space and when this occurs it will dump the contents of A into B as a [list], which will be a full word, and then RESET A to '', that way it will continue to read char by char the next word.
By the end of the loop, B will contain each word of the string as items in a list and return.
To answer your other question, yes strings do have index positions. If you
print('Hello World'[0:5])
This will return: Hello
Code:
def mysplit(strng):
A = ""
B = []
for i in strng: #Loop through each char in string
if i != " ": #if char is not a space
A += i #add character to A
elif A != "": #if A is not empty
B.append(A) #add whatever is in A to B as a list (full word)
A = "" #resets A to be empty
if A != "": #if A is empty
B.append(A)
return B #return is a statement, so it doesn't require parenthesis.

Yes, strings have index from 0 to n-1 just like in a string.
Eg: A = "abcd", print(a[2]) //output: "c"
As for your code, i iterates through every element in the input string, and it is appended to A if i is not a "space". When it is a "space", A is appended to B list and A is cleared in order to get the next word. For the last word, since there is no space in the end, the string A does not get appended to B list, so it is done separately outside the for loop.

Related

replace text python 2 leters replace [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I only want to change the text when there are both letters
def replaceonce(s, letters = '', replacewith=''):
letters = set(letters)
res = ''
for l in s:
if l in letters:
res += replacewith
letters.remove(l)
replacewith = ''
else:
res += l
return res
print(replaceonce('yday',letters='ya',replacewith='z'))
this code change to zdy although there is a letter and is not in text
print(replaceonce('yday',letters='ya',replacewith='z'))
output
ydz or dyz or zyd all combinations are ok fine
I want the text to change as well
that it will look like this
azdry
output
or another order of letters
zdrz
if two letters will appear in the text to change only if there are both letters, so y + and in this example
The following code returns the expected outputs for both the examples:
def findIndexes(string, letters):
indexes = []
for c in letters:
for i in range(len(string)):
if string[i] == c:
indexes.append(i)
break
return indexes
def replaceonce(s, letters = '', replacewith=''):
allPresent = True
toRet = ''
# checking if all letters' chars are in s
for c in letters:
if c not in s:
allPresent = False
break
if allPresent:
# this block make the substitution
# getting the index of first occurrence of each
# letters' char inside the s string
indexes = findIndexes(s, letters)
for i in range(len(s)):
if i not in indexes:
toRet += s[i]
toRet += replacewith
return toRet
Your examples make the substitution for one occurrence of the letters string, even if the string is splitted somewhere inside the s. Then the idea is: find the index where this chars are and skip all of them when reconstruct the s string. At the end of code, add the replaceWith at the end of reconstructed string.
I hope that I understood correctly your question that, by the way, was not very clear.

TypeError: list indices must be integers or slices, not str? Hangman [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
The problem starts on this part of the code when I want to replace an underscore from the w list with he found a letter from the myword string, I don't want to look up the whole hangman solution though! Any suggestions?
while t == 0:
for i in myword:
if guess == i:
t = 1
w[i] = i
print(w)
i is a single character from the string, so w[i] won't work -- as the error states, you can't use a string to slice another string.
Instead, you can use enumerate to get both the letter and the letter's index at the same time:
while t == 0:
for idx, letter in enumerate(myword):
if guess == letter:
t = 1
w[idx] = letter
print(w)
If you are iterating over a string myword, your i is actually a letter, so i is a string. So you could have index if this letter with enumerate without any runtime overhead (like getting an index of the letter with myword.index(letter)):
while t == 0:
for index, letter in enumerate(myword):
if guess == letter:
t = 1
w[index] = letter
print(w)
You don't need a while loop to stop iteration. There is a keyword break exactly for this case:
for index, letter in enumerate(myword):
if guess == letter:
w[index] = letter
print(w) # this will print w on each finding the guess
break
Like in the answer above/below, you can use enumerate to access each element aligned with its index in the string.
But if you are not familiar with enumerate, you can use str.index():
while t == 0:
for i in myword:
if guess == i:
t = 1
w[myword.index(i)] = i
print(w)

Take in integer and string using input() and check for conditions [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I needed help with this problem here in python:
Write a program which accepts an integer N and N strings each on a newline. Check for the below conditions and perform the respective operations:
The string contains only one word then capitalize the whole string
The string contains exactly 2 words capitalize only the first character of each word
The string contains more than two words toggle case of the string
Your task is to print each string in a newline after performing the respective operations.
Input Format:
The first line will contain an integer N, specifying the number of strings
The next N lines will contain one string each
Output Format:
String after performing the respective operation in a newline.
Example #1:
Input:
3 #number of input words
Hello #1st input
My name is #2nd input
adam smith #3rd input
Output:
HELLO
mY NAME IS
Adam smith
This solution will work:
num=int(input())
words=[]
for a in range(0,num):
words.append(input())
for word in words:
if len(word.split())==1:
print(word.upper())
elif len(word.split())==2:
print(word.title())
elif len(word.split())>2:
print(word.swapcase())
if you are trying to attempt a HackerRank challenge or any other code challenge, i would strongly recommend first building small programs then attempting those.
It seems that you would have to look through a multi-line string to get the input.
So a sample string would look something like:
sample = """
3
Hello
My name is
adam smith
"""
Now, to find the number of words in one line of each string...
There is a built-in string function called split(), but I'm going to do the basic version:
def toWords(string):
newlist = [] # create a list we can add things to with ".append()"
newstr = '' # initial string
for i in string:
if i == ' ': # When we come across a space
newlist.append(newstr) # Add what's been accumulated to list
newstr = '' # Start over
else:
newstr += i # Accumulate
if newstr:
newlist.append(newstr)
return newlist # Finally, return the value
We also need a way to split up the multi-line string:
my_list = sample.split('\n') # where '\n' is the newline character
Last, we add the rules:
def all(string):
acc = "" #acc for accumulator
my_list = string.split('\n')
toggle = 1
number = int(my_list[0])
for i in my_list[1:]:
if len(toWords(i)) == 1:
acc += toWords(i)[0].lower() + ' '
elif len(toWords(i)) == 2:
acc += toWords(i)[0].capitalize() + toWords(i)[1].capitalize() + ' '
else:
for char in i:
toggle = toggle * -1
if toggle == 1:
acc += char
acc += ' '
return acc

Printing out a word if it has a specific letter in it? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
How would i print out a word in a list or string that has a specific letter in it?
e.g.
Letter: e
Input: I need help with my program
need help
See how it printed out "need help" because those words have "e" in them? Help :)
My workaround:
a = input("Letter: ")
b = input("Input: ")
c = b.count(a)
print(c)
d = b.split()
for e in d:
print(e,end=" ")
Why not simply:
a = input("Letter: ")
b = input("Input: ")
words = b.split()
for word in words:
if a in word:
print(word)
You almost had it. In your for loop, now you just need a conditional.
A conditional is a statement which determines whether something is True or False.
You probably want:
for e in d:
if a in e:
print(e)
You can check if a character (or substring) is in a string using in:
letter = input("Letter: ")[0] # Limit to one character
words = input("Text: ").split()
for word in words:
if letter in word:
print(word, end=" ")
print() # Add newline
Addendum (see the comments):
To remove the final space, you can accumulate the words in a string and then remove it
letter = input("Letter: ")[0] # Limit to one character
words = input("Text: ").split()
output = ""
for word in words:
if letter in word:
output += word + " "
print(output.rstrip()) # Print without trailing whitespace
or (which I would discourage, because it makes the intention less obvious) check if you are encountering the last word and print a newline instead of the additional space (so you don't need the additional print().
letter = input("Letter: ")[0] # Limit to one character
words = input("Text: ").split()
for index in range(len(words)):
if letter in words[index]:
the_end = "\n" if index == len(words) - 1 else " " # Newline only if it is the last word
print(word, end=the_end)

word separator for python coding [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
So the question reads:
Write a program that accepts as input a sentence in which all of the words are run together but the first character of each word is uppercase. Convert the sentence to a string in which the words are separated by spaces and only the first word starts with an uppercase letter. For example the string "StopAndSmellTheRoses." would be converted to " Stop and smell the roses."
I am so confused this my code so far.
def main():
#User enters a sentence
my_string=input('enter a sentence: ')
print(my_string.capitalize())
main()
You can loop through the string and add a character each time to a result:
my_string = "StopAndSmellTheRoses"
i = 0
result = ""
for c in my_string:
if c.isupper() and i > 0:
result += " "
result += c.lower()
else:
result += c
i += 1
print result
We'll use c for each character as we walk through the string and we'll use i to keep track of the position in the string.
There are two possibilities: it's either an uppercase character (excluding the first one) or it's not.
In the first case we'll add a space and that character as lowercase to the result. This ensures a space is inserted before each uppercase character further in the sentence.
In the second case it's a lowercase character or the uppercase character at the beginning of the sentence. We don't have to do anything with these and we'll add it right away.
Lastly we add one to i whenever we're done with a character (i += 1) as this means we correctly know where we are in the sentence.
Welcome to SO!
One way to do this is to loop through your string, checking the chars one by one:
#You've learned how to iterate through something, right?
i = 0 #a counter
for c in my_string: #get the characters of my_string, one by one.
if c.isupper(): #check if it's in upper case
if i == 0: #if it's the first letter
new_string += c #let it be like the original
else:
new_string += ' '+.lower() #it's not the first letter,
#so add space, and lower the letter.
else:
new_string += c #else, only add the letter to the new string
i += 1
Edit added a double-check to see if it's the first letter of the sentence or not. Updated demo.
As an alternative to using a counter, you can also use the built-in function enumerate, which returns a tuple of index and values.
for i,c in enumerate(my_string): #get the characters of my_string, one by one.
if c.isupper(): #check if it's in upper case
if i == 0: #if it's the first letter
new_string += c #let it be like the original
else:
new_string += ' '+c.lower() #it's not the first letter,
#so add space, and lower the letter.
else:
new_string += c #else, only add the letter to the new string
Demo
>>> my_string = 'ImCool'
>>> new_string = ''
>>> i = 0 #a counter
>>> for c in my_string: #get the characters of my_string, one by one.
if c.isupper(): #check if it's in upper case
if i == 0: #if it's the first letter
new_string += c #let it be like the original
else:
new_string += ' '+.lower() #it's not the first letter,
#so add space, and lower the letter.
else:
new_string += c #else, only add the letter to the new string
i += 1
>>> new_string
'Im cool'
Hope this helps!
You'll need a bit of regex.
import re
split = re.findall(r'[A-Z][a-z\.]+', 'HelloThisIsMyString.')
You'll also need to join those together (inserting spaces)
' '.join(...)
and handle case conversions
' '.join(word.lower() for word in split)
(and as you already did, capitalize the first word)
' '.join(word.lower() for word in split).capitalize()
It appears that you are a little confused and this is to be expected if you are new to Python. I'm assuming you take input from the user as opposed to input for a function. Either way I would create a simple function that you could insert the users input into. The function below will accomplish what the problem asks.
def sentenceSplitter(sentence):
result = ""
for i, x in enumerate(sentence): #i is character index, x is the element
if i == 0:
result = result + x
elif x.isupper() == False: #if element is not uppercase, add it to the result
result = result + x
else: # Otherwise, add a space and lowercase the next letter
result = result + " " +x.lower()
return(result)
To reiterate, if you are looking to print out the sentence you would write this after the function:
def main():
#User enters a sentence
my_string=input('enter a sentence: ')
print(sentenceSplitter(my_string))
main()
If you are still confused feel free to ask any further questions.

Categories

Resources