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.
Related
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 5 months ago.
Improve this question
word2 = input("put in the word you want me to repeat: ")
letter = ""
print("The original string is: " + word2)
for x in range(len(word2)):
letter += word2[x]
So if i put in "dwas" it will just print "dwas". How do I make it print "d-ww-aaa-ssss"?
You can use enumerate passing the string value from input, and the start value as 1, then repeat the characters n times, and finally join by -:
>>> print('-'.join(v*i for v,i in enumerate(inp,1)))
d-ww-aaa-ssss
By composiing built-in functions:
s = "hallo"
new_s = '-'.join(map(str.__mul__, s, range(1, len(s)+1)))
print(new_s)
#h-aa-lll-llll-ooooo
A for loop approach similar to the one in the question
s = "hallo"
# construct the output character per character
new_s = ''
# iterate over (index, character)-pairs, index start from 1
for i, char in enumerate(s, 1):
# add to output i-times the same character followed by -
new_s += f'{char*i}-'
# remove the last character (always the -)
new_s = new_s.rstrip('-')
# check result
print(new_s)
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.
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'm trying to add random letters after each letter in a given range, but they aren't in complete randomness.
def add_letters(org,num):
new_word = ''
for i in org:
randomLetter = random.choice(string.ascii_letters) * num
new_word += i
new_word += randomLetter
return new_word
original = 'Hello!'
for num in range(1,5):
#scramble the word using 'num' extra characters
scrambled = add_letters(original,num)
#output
print("Adding",num,'random characters to',original,'->',scrambled)
some of the results will have the same letter repeating multiple times like "HAAAAeiiiilzzzzlBBBBoSSSS!jjjj". Instead, they should be random.
You used *sum, which only generate randomLetter once and repeat the result letter for sum times. It's not repeat the random generation. So the result repeated.
It should be a loop or list-comprehension to generate mutiple randomLetter.
fixed code:
import random
import string
def add_letters(org,num):
new_word = ''
for i in org:
randomLetter = "".join(random.choice(string.ascii_letters) for _ in range(num))
new_word += i
new_word += randomLetter
return new_word
original = 'Hello!'
for num in range(1,5):
#scramble the word using 'num' extra characters
scrambled = add_letters(original,num)
#output
print("Adding",num,'random characters to',original,'->',scrambled)
result:
Adding 1 random characters to Hello! -> HNemldlgos!z
Adding 2 random characters to Hello! -> HVTeGYlYLlxdonV!GM
Adding 3 random characters to Hello! -> HqjbeQyOlgfHlAwqoyCj!PRq
Adding 4 random characters to Hello! -> HyFoLeyHUzlExGelVLlAoOhyz!EuzW
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
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 5 years ago.
Improve this question
I'm just beginning to learn Python, so please bear with me. My math knowledge is a little shaky as well. I'm able to capitalize a single word, or first word in a string. What I am having a problem with is i need to capitalize every 3rd letter in the string. I need to do this as a function.
I've used something like this, but can only get this to change the letter in one word, not every 3rd.
x = "string"
y = x[:3] + x[3].swapcase() + x[4:]
There is a sample template that used
if i in phrase (len(phrase))
But i'm not sure how that works.
I'd like an output to show something like "thIs tExtIng fuNctIon"
Thanks in advance for any help.
You can take a stride slice of an array which makes for a pretty and pythonic few lines:
s = "thisisareallylongstringwithlotsofletters"
# convert to list
a = list(s)
#change every third letter in place with a list comprehension
a[2::3] = [x.upper() for x in a[2::3]]
#back to a string
s = ''.join(a)
# result: thIsiSarEalLylOngStrIngWitHloTsoFleTteRs
It's not clear what you want with spaces - this treats them like characters.
Since you want every 3rd letter and not just the 3rd letter, we need to iterate the letters and generate the result according to the position of the character:
def cap_3rd(word):
result = ""
for i in range(1, len(word) + 1):
if i % 3 == 0:
result += word[i-1].upper()
else:
result += word[i-1]
return result
word = "thisisaverylonglongword"
print(cap_3rd(word)) # thIsiSavEryLonGloNgwOrd
x = "string"
z = list(x)
for x in range(2,len(z),3): # start from 3rd (index2) and step by 3
z[x] = z[x].upper()
x = ''.join(z)
print x
Output: StrIng
If you don't care about letters and spaces:
''.join(phrase[i-1] if i % 3 or i == 0 else phrase[i-1].upper() for i in range(1, len(phrase) + 1))
If you only want to count letters:
new_phrase = ''
phrase = "here are some words"
counter = 0
for c in phrase:
if not c.isalpha():
new_phrase += c
else:
counter += 1
if not counter % 3:
new_phrase += c.upper()
else:
new_phrase += c
Since your example shows you using swapcase() instead of upper(), you can just replace upper() with swapcase() in this code to achieve that functionality if that's what you want.
Try applying some split, and a lambda as below, and then join.
>>> x = "this texting function"
>>> " ".join(map(lambda w: w[:2] + w[2].swapcase() + w[3:], x.split()))
'thIs teXting fuNction'
If you are not a fan of lambda, then you can write a method like this
>>> def swapcase_3rd(string):
... if len(string) >3:
... return string[:2] + string[2].swapcase() + string[3:]
... if len(string) == 3:
... return string[:2] + string[2].swapcase()
... return string
...
>>> x = "this texting function"
>>> " ".join(map(swapcase_3rd, x.split()))
'thIs teXting fuNction'