Got stuck with a part of the python script. For example I got 2 domain names like:
domain.com
new.domain1.us
is it possible to count word lenght of every word, splited with dot and put the lenght in brackets before every word like:
(6)domain(3)com
(3)new(7)domain1(2)us
string = 'domain.com'
answer = ''
for x in string.split('.'):
answer += '(' + str(len(x)) + ')' + x
print(answer)
The method split() will split the string at the given char into an array of strings.
len() will return you the length of the given string/array/...
With these two functions you can solve your problem:
domain = "www.google.de"
split_domain = domain.split('.')
domain_with_len = ""
for part in split_domain:
domain_with_len += "(" + str(len(part)) + ")" + part
if you print the domain_with_len you get the following result:
(3)www(6)google(2)de
Related
str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
Like I want to extract I Love Python from this string. But I am not getting how to.
I tried to loop in str1 but not successful.
i = str1 .index("I")
for letter in range(i, len(mystery11)):
if letter != " ":
letter = letter+2
else:
letter = letter+3
print(mystery11[letter], end = "")
In your for loop letter is an integer. In the the first line of the loop you need to compare mystery[11] with " ":
if mystery11[letter] != " ":
You can use a dict here, and have char->freq mapping of the sentence in it and create a hash table.
After that you can simply iterate over the string and check if the character is present in the hash or not, and if it is present then check if its count is greater than 1 or not.
Don't know if this will solve all your problems, but you're running your loop over the indices of the string, This means that your variable letter is an integer not a char. Then, letter != " " is always true. To select the current letter you need to do string[letter]. For example,
if mystery11[letter] != " ":
...
Here's how I'd go about:
Understand the pattern of the input: words are separated by blank spaces and we should get every other letter after the first uppercase one.
Convert string into a list;
Find the first uppercase letter of each element and add one so we are indexing the next one;
Get every other char from each word;
Join the list back into a string;
Print :D
Here's the code:
def first_uppercase(str):
for i in range(0, len(str)):
if word[i].istitle():
return i
return -1
def decode_every_other(str, i):
return word[i::2]
str1 = "srbGIE JLWokvQeR DPhyItWhYolnz"
# 1
sentence = str1.split()
clean_sentence = []
for word in sentence:
# 2
start = first_uppercase(word) + 1
# 3
clean_sentence.append(decode_every_other(word, start))
# 4
clean_sentence = ' '.join(clean_sentence)
print("Input: " + str1)
print("Output: " + clean_sentence)
This is what I ended up with:
Input: srbGIE JLWokvQeR DPhyItWhYolnz
Output: I Love Python
I've added some links to the steps so you can read more if you want to.
def split(word):
return [char for char in word]
a = input("Enter the original string to match:- ")
b = input("Enter the string to lookup for:- ")
c = split(a)
d = split(b)
e = []
for i in c:
if i in d:
e.append(i)
if e == c:
final_string = "".join(e)
print("Congrats!! It's there and here it is:- ", final_string)
else:
print("Sorry, the string is not present there!!")
I am trying to write a short python function to break a long one_line string into a multi_line string by inserting \n. the code works fine when i simply insert \n into the string but i get an index out of range error when i insert a conditional check to add hyphenation as well. Here is the code that i have written.
Sentence = "Python string comparison is performed using the characters in both strings. The characters in both strings are compared one by one. When different characters are found then their Unicode value is compared. The character with lower Unicode value is considered to be smaller."
for i in range(1, int(len(Sentence)/40)+1):
x = i*40
Sentence = Sentence[:x] + "\n" if Sentence[x] == " " else "-\n" + Sentence[x:]
print(Sentence)
Here is the error message i get.
Traceback (most recent call last):
File "/media/u1/data/prop.py", line 4, in <module>
Sentence = Sentence[:x] + "\n" if Sentence[x] == " " else "-\n" + Sentence[x:]
IndexError: string index out of range
The conditional expression is greedy, parsed as if you had written
Sentence = Sentence[:x] + \
("\n" if Sentence[x] == " " else "-\n" + Sentence[x:])
As a result, you are doing one of two operations:
Sentence[:x] + '\n' if you find a space
Sentence[:x] + "-\n" + Sentence[x:] if you find a different character.
Note that case 1 shortens your sentence incorrectly, but your range object is based on the original correct list.
The solution is to use parentheses to define the conditional expression correctly:
for i in range(1, int(len(Sentence)/40)+1):
x = i*40
c = Sentence[x]
Sentence = Sentence[:x] + (f"\n" if c == " " else f"{c}-\n") + Sentence[x+1:]
# ^ ^
Well the issue might not be obvious in the start but when you start looking at the if statement in the middle of string concatenation, you will understand. For a minute just focus on the following line:
Sentence = Sentence[:x] + "\n" if Sentence[x] == " " else "-\n" + Sentence[x:]
Python would parse this statement like so:
Sentence = (Sentence[:x] + "\n") if Sentence[x] == " " else ("-\n" + Sentence[x:])
Notice the brackets carefully. This is exactly the reason why the length of the string held by the variable Sentence is decreasing after each iteration which triggers the IndexError exception. Hence, in order to address this issue, we will have to explicitly tell Python what we are expecting. So, it could be written as such:
Sentence = Sentence[:x] + ("\n" if Sentence[x] == " " else "-\n") + Sentence[x:]
string = "Python string comparison is performed using the characters in both strings. The characters in both strings are compared one by one. When different characters are found then their Unicode value is compared. The character with lower Unicode value is considered to be smaller."
stc = ""
for j in range(1 + len(string) // 40):
stc += string[j * 40:40 * (j + 1)] + "\n"
print(stc)
I want to write a function that will take a string and turn the words into Pyg Latin. That means that:
If a word begins with a vowel, add "-way" to the end. Example: "ant" becomes "ant-way".
If a word begins with a consonant cluster, move that cluster to the end and add "ay" to it. Example: "pant" becomes "ant-pay".
I've searched many posts and websites but none of them do the same way or the way I want to do it. I have to test these functions in a test and I have 4 test cases for this one. One is 'fish' and it should returns 'ish-fray' the second is 'frish' and it should returns 'ish-fray' the third is 'ish' and it should return 'ish-way' and the last is 'tis but a scratch' and it should return 'is-tay ut-bay a-way atch-scray'
I've found a program that can translate it CLOSE to what it has to be but I'm not sure how to edit it so it can return the result I'm looking for.
def pyg_latin(fir_str):
pyg = 'ay'
pyg_input = fir_str
if len(pyg_input) > 0 and pyg_input.isalpha():
lwr_input = pyg_input.lower()
lst = lwr_input.split()
latin = []
for item in lst:
frst = item[0]
if frst in 'aeiou':
item = item + pyg
else:
item = item[1:] + frst + pyg
latin.append(item)
return ' '.join(latin)
So, this is the result my code does:
pyg_latin('fish')
#it returns
'ishfay'
What I want it to return isn't much different but I dont know how to add it in
pyg_latin('fish')
#it returns
'ish-fay'
Think about what the string should look like.
Chunk of text, followed by a hyphen, followed by the first letter (if it’s a not a vowel), followed by “ay”.
You can use python string formatting or just add the strings together:
Item[1:] + “-“ + frst + pyg
It is also worth learning how array slicing works and how strings are arrays that can be accessed through the notation. The following code appears to work for your test cases. You should refactor it and understand what each line does. Make the solution more robust but adding test scenarios like '1st' or a sentence with punctuation. You could also build a function that creates the pig latin string and returns it then refactor the code to utilize that.
def pg(w):
w = w.lower()
string = ''
if w[0] not in 'aeiou':
if w[1] not in 'aeiou':
string = w[2:] + "-" + w[:2] + "ay"
return string
else:
string = w[1:] + "-" + w[0] + "ay"
return string
else:
string = w + "-" + "way"
return string
words = ['fish', 'frish', 'ish', 'tis but a scratch']
for word in words:
# Type check the incoming object and raise an error if it is not a list or string
# This allows handling both 'fish' and 'tis but a scratch' but not 5.
if isinstance(word, str):
new_phrase = ''
if ' ' in word:
for w in word.split(' '):
new_phrase += (pg(w)) + ' '
else:
new_phrase = pg(word)
print(new_phrase)
# Raise a Type exception if the object being processed is not a string
else:
raise TypeError
I stuck on the following lab exercise:
The first piece we need is a routine that, given a word, will in
someway jumble up the order of all but the first and the last
characters. Rather than just randomly moving the characters around we
will reverse the order of the letters. The following code achieves
this:
def jumble(x):
return x[len(x)::-1]
my_string="Alistair"
print(" Reverse ",jumble(my_string))
Copy the above code to a file and run it. Currently it reverses the
order of all the characters in "my_string". Modify the code so that
the first and last letters of the word are NOT reversed. That is,
instead of producing "riatsilA" it produces "Aiatsilr".
This is my code for the above part:
def jumble(x):
temp0=x[0]
temp_last=x[-1]
x_new=temp0 + x[-2:0:-1] + temp_last
return x_new
my_string="Alistair"
print(" Reverse ",jumble(my_string))
The above routine does not account for leading or trailing white
space, punctuation or other characters that might legitimately be part
of the character string, but that should not be jumbled up. For
example if the string were " Alistair, " the result should be
" riatsilA, ". Modify your routine so that only the FIRST contiguous
series of alphabetical characters (minus the first and last
characters) are reversed. Ensure that the final returned string
includes all other leading and trailing characters.
I am not sure how to do this, as white space and punctuations can happen anywhere, I am thinking about have two lists, one for empty space and punctuations while another one for "contigous series of alphabetical characters", using append method to append elements to each list, but not sure how to preserve index.Can someone help me out? Thanks in advance.
#!/usr/bin/env python
#-*-coding:utf-8-*-
import re
def reverse(s):
p = re.compile(r'\w+')
for m in p.finditer(s):
word = m.group()
if word:
p = s.partition(word)
l = list(p)
index = p.index(word)
l[index] = l[index][::-1]
l2 = list(l[index])
l2[0],l2[-1]=l2[-1],l2[0]
l[index]=''.join(l2)
s = ''.join(l)
return s
s="Alistair Chris,"
print reverse(s)
fixed it.
The following code snipplet might help you for the last task.
There's no special handling for reverting of subsets, if a special char is found somewhere else than at start or end of the string.
# Special chars which should be ignored for reverting
SPECIALCHARS = [' ', '.', ',']
def reverse( string_ ):
# Find occurence of 'special' chars. Stack position and char into a list.
specchar = [( i, ltr ) for i, ltr in enumerate( string_ ) if ltr in SPECIALCHARS]
if specchar:
# Remove all the special characters
newstring = ''.join( c for c in string_ if c not in SPECIALCHARS )
# Reverse the legal characters
newstring = newstring[::-1]
offset = 0
# Re-insert the removed special chars
for pos, char in specchar:
if pos + 1 + offset >= len( newstring ):
# Append at the end
newstring += char
else:
# Insert
newstring = newstring[:pos + offset] + char + newstring[pos + offset:]
offset += 1
return newstring
else: # No special char at all, so just revert
return string_[::-1]
print " '%s' =?= ' riatsilA, '" % ( reverse( " Alistair, " ) )
will lead to the following output: ' riatsilA, ' =?= ' riatsilA, '
Just reverting with ignoring the first and last char is a one liner.
Using this one to invert the 'middle': t[1:-1][::-1]
Then add the first and last char to it.
>>> t = "Alistair"
>>> t[0]+t[1:-1][::-1]+t[-1]
'Aiatsilr'
Edit
Ok, now I think I understood what you want :-)
newstr = ""
fullstr = ""
for char in mystr:
if char in SPECIALCHARS:
if len( newstr ): # Is already something to invert there?
#Ignore 1st and last char and revert the rest
newstr = newstr[0] + newstr[1:-1][::-1] + newstr[-1]
fullstr += newstr + char
else: # Special char found but nothing to revert so far
fullstr += char
newstr = ""
else: # No special char so just append
newstr += char
print "'%s'" % fullstr
I tried this: Capitalize a string. Can anybody provide a simple script/snippet for guideline?
Python documentation has capitalize() function which makes first letter capital. I want something like make_nth_letter_cap(str, n).
Capitalize n-th character and lowercase the rest as capitalize() does:
def capitalize_nth(s, n):
return s[:n].lower() + s[n:].capitalize()
my_string[:n] + my_string[n].upper() + my_string[n + 1:]
Or a more efficient version that isn't a Schlemiel the Painter's algorithm:
''.join([my_string[:n], my_string[n].upper(), my_string[n + 1:]])
x = "string"
y = x[:3] + x[3].swapcase() + x[4:]
Output
strIng
Code
Keep in mind that swapcase will invert the case whether it is lower or upper.
I used this just to show an alternate way.
This is the comprehensive solution: either you input a single word, a single line sentence or a multi line sentence, the nth letter will be converted to Capital letter and you will get back the converted string as output:
You can use this code:
def nth_letter_uppercase(string,n):
listofwords = string.split()
sentence_upper = ''
for word in listofwords:
length = len(word)
if length > (n - 1):
new_word = word[:n-1] + word[n-1].upper() + word[n:]
else:
new_word = word
sentence_upper += ' ' + new_word
return sentence_upper
calling the function defined above (I want to convert 2nd letter of each word to a capital letter):
string = '''nature is beautiful
and i love python'''
nth_letter_uppercase(string,2)
output will be:
'nAture iS bEautiful aNd i lOve pYthon'
I know it's an old topic but this might be useful to someone in the future:
def myfunc(str, nth):
new_str = '' #empty string to hold new modified string
for i,l in enumerate(str): # enumerate returns both, index numbers and objects
if i % nth == 0: # if index number % nth == 0 (even number)
new_str += l.upper() # add an upper cased letter to the new_str
else: # if index number nth
new_str += l # add the other letters to new_str as they are
return new_str # returns the string new_str
A simplified answer would be:
def make_nth_letter_capital(word, n):
return word[:n].capitalize() + word[n:].capitalize()
You can use:
def capitalize_nth(text, pos):
before_nth = text[:pos]
n = text[pos].upper()
new_pos = pos+1
after_nth = text[new_pos:]
word = before_nth + n + after_nth
print(word)
capitalize_nth('McDonalds', 6)
The outcome is:
'McDonaLds'
I think this is the simplest among every answer up there...
def capitalize_n(string, n):
return string[:n] + string[n].capitalize() + string[n+1:]
This works perfect