Python add spaces between letters but not between other characters? - python-3.x

I'm looking to have a function that adds spaces in between letters, but doesn't add any spaces between other characters (for example not between a "2" and a letter, or between a letter and an apostrophe). The input strings already have spaces after any non-letter character.
For example, given the string "RU2 FLB' L2 r2 fB'", the output would be "R U2 F L B' L2 r2 f B'".
Thanks for any help :)

you can use this code, very simple and understandable, you can change it to a function or use by lambda and so on...
my_string = "RU2 FLB' L2 r2 fB" #or any input
output = '' #your output
num = ['1','2','3','4','5','6','7','8','9','0','\''] #you can add any other symbols may use in your string
for i in range(len(my_string)):
if my_string[i] == ' ':
continue
elif i < (len(my_string) -1) and num.count(my_string[i+1]) > 0:
output = output + my_string[i]
continue
elif my_string[i]:
output = output + my_string[i] + ' '
print(output)

Related

Why I am not able to Iterate my first FOR loop

I am writing a python code to find all possible combinations of password with specific rules
should contain alphabets A-Z a-z
should contain numbers 0-9
should contain special symbols
first character of password must be capital letter
from itertools import permutations
pw = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789[#_!#$%^&*()<>?/\|}{~:]"
firstchar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
c = permutations(pw, 2) #3 is the password length for providing sample output quickly
f=open("password.txt","w+")
f.truncate(0)
for x in firstchar:
for i in c:
current_pw = x + "".join(i)
f.write( "\t" + current_pw + "\n" )
**
the output contains only password starting from A and stops doesn't iterate for B, C...
**
I think permutation quits after the first loop.
So you define c in each loop.
from itertools import permutations
pw = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789[#_!#$%^&*()<>?/\|}{~:]"
firstchar = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
f=open("password.txt","w+")
f.truncate(0)
for x in firstchar:
c = permutations(pw, 2) # c is defined here
for i in c:
current_pw = x + "".join(i)
f.write( "\t" + current_pw + "\n" )

Can we use for loop and if else in a single lambda function at once? so it can check values while working inside loop

Have the function LetterChanges(str). Take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a).
Then capitalize every vowel in this new string (a, e, i, o, u) and finallyreturn this modified string.
I want this problem done in 2 lines
a= lambda stri:([(chr(ord(i) + 1)) for i in stri]) #if i not in ("a","e","i","o","u")
print(a("bcdefgh"))
I know that if part is wrong, to understand clearly, I included it in comment.
Expected output is "cdEfgI".
Your expected output does not match your input, you are missing an h before the final I.
Assuming this is just a typo, your problem can be solved with:
>>> a = lambda stri: ''.join('A' if i == 'z' else chr(ord(i) + (-31 if i in "dhnt" else 1)) for i in stri)
>>> print(a("bcdefgh"))
cdEfghI
Explanation:
first check if i is a z then return an A
otherwise check if i is any character preceding a vowel in the alphabet then subtract 31 from it to get the capitalized vowel
if that is not the case, increase the character by one
Here's the normal code (that you should have already made):
def change_letters(string):
result = ''
for letter in string:
# This makes sure that 'z' goes to 'a'
next_letter = chr((ord(letter) - 98)%26 + 97)
if next_letter in 'aeiou':
result += letter.upper()
else:
result += letter
return string
If we follow the steps in my other answer here, we end up with the following:
change_letters = lambda string: ''.join(chr((ord(letter) - 98)%26 + 97).upper() if chr((ord(letter) - 98)%26 + 97) in 'aeiou' else chr((ord(letter) - 98)%26 + 97) for letter in string)
But please note, this is a HORRIBLE thing to do, especially for your future self and others you may one day be working with. I would not want to see this again :)

hello friends i cant execute my else condition

The program must accept a string S as the input. The program must replace every vowel in the string S by the next consonant (alphabetical order) and replace every consonant in the string S by the next vowel (alphabetical order). Finally, the program must print the modified string as the output.
s=input()
z=[let for let in s]
alpa="abcdefghijklmnopqrstuvwxyz"
a=[let for let in alpa]
v="aeiou"
vow=[let for let in v]
for let in z:
if(let=="a"or let=="e" or let=="i" or let=="o" or let=="u"):
index=a.index(let)+1
if index!="a"or index!="e"or index!="i"or index!="o"or index!="u":
print(a[index],end="")
else:
for let in alpa:
ind=alpa.index(let)
i=ind+1
if(i=="a"or i=="e" or i=="i"or i=="o"or i=="u"):
print(i,end="")
the output is :
i/p orange
pbf
the required output is:
i/p orange
puboif
I would do it like this:
import string
def dumb_encrypt(text, vowels='aeiou'):
result = ''
for char in text:
i = string.ascii_letters.index(char)
if char.lower() in vowels:
result += string.ascii_letters[(i + 1) % len(string.ascii_letters)]
else:
c = 'a'
for c in vowels:
if string.ascii_letters.index(c) > i:
break
result += c
return result
print(dumb_encrypt('orange'))
# puboif
Basically, I would use string.ascii_letters, instead of defining that anew. Also, I would not convert all to list as it is not necessary for looping through. The consonants you got right. The vowels, I would just do an uncertain search for the next valid consonant. If the search, fails it sticks back to default a value.
Here I use groupby to split the alphabet into runs of vowels and consonants. I then create a mapping of letters to the next letter of the other type (ignoring the final consonants in the alphabet). I then use str.maketrans to build a translation table I can pass to str.translate to convert the string.
from itertools import groupby
from string import ascii_lowercase as letters
vowels = "aeiou"
is_vowel = vowels.__contains__
partitions = [list(g) for k, g in groupby(letters, is_vowel)]
mapping = {}
for curr_letters, next_letters in zip(partitions, partitions[1:]):
for letter in curr_letters:
mapping[letter] = next_letters[0]
table = str.maketrans(mapping)
"orange".translate(table)
# 'puboif'

How would I reverse each word individually rather than the whole string as a whole

I'm trying to reverse the words in a string individually so the words are still in order however just reversed such as "hi my name is" with output "ih ym eman si" however the whole string gets flipped
r = 0
def readReverse(): #creates the function
start = default_timer() #initiates a timer
r = len(n.split()) #n is the users input
if len(n) == 0:
return n
else:
return n[0] + readReverse(n[::-1])
duration = default_timer() - start
print(str(r) + " with a runtime of " + str(duration))
print(readReverse(n))
First split the string into words, punctuation and whitespace with a regular expression similar to this. Then you can use a generator expression to reverse each word individually and finally join them together with str.join.
import re
text = "Hello, I'm a string!"
split_text = re.findall(r"[\w']+|[^\w]", text)
reversed_text = ''.join(word[::-1] for word in split_text)
print(reversed_text)
Output:
olleH, m'I a gnirts!
If you want to ignore the punctuation you can omit the regular expression and just split the string:
text = "Hello, I'm a string!"
reversed_text = ' '.join(word[::-1] for word in text.split())
However, the commas, exclamation marks, etc. will then be a part of the words.
,olleH m'I a !gnirts
Here's the recursive version:
def read_reverse(text):
idx = text.find(' ') # Find index of next space character.
if idx == -1: # No more spaces left.
return text[::-1]
else: # Split off the first word and reverse it and recurse.
return text[:idx][::-1] + ' ' + read_reverse(text[idx+1:])

Counting the number of capital letters in an input?- in python

On python how do you make a program that asks for an input and the program works out the number of capital letters in that input and output the number of capital letters?
Loop through the string and use .isupper() to check if the letter is uppercase and increment the count. Finally print the count.
inpt = raw_input('Enter something: ')
c = 0
for i in inpt:
if i.isupper():
c += 1
print "No. of uppercase letters: ", c
len(filter(lambda x:isupper(x),list(input("Enter String"))))
Try the following function:
def capital(word):
num = 0
for char in word:
if char.isupper():
num+=1
return num
And incorporate it as such:
word = input('Enter: ')
print capital(word)

Resources