String reverse in Python - python

Write a simple program that reads a line from the keyboard and outputs the same line where
every word is reversed. A word is defined as a continuous sequence of alphanumeric characters
or hyphen (‘-’). For instance, if the input is
“Can you help me!”
the output should be
“naC uoy pleh em!”
I just tryed with the following code, but there are some problem with it,
print"Enter the string:"
str1=raw_input()
print (' '.join((str1[::-1]).split(' ')[::-2]))
It prints "naC uoy pleh !em", just look the exclamation(!), it is the problem here. Anybody can help me???

The easiest is probably to use the re module to split the string:
import re
pattern = re.compile('(\W)')
string = raw_input('Enter the string: ')
print ''.join(x[::-1] for x in pattern.split(string))
When run, you get:
Enter the string: Can you help me!
naC uoy pleh em!

You could use re.sub() to find each word and reverse it:
In [8]: import re
In [9]: s = "Can you help me!"
In [10]: re.sub(r'[-\w]+', lambda w:w.group()[::-1], s)
Out[10]: 'naC uoy pleh em!'

My answer, more verbose though. It handles more than one punctuation mark at the end as well as punctuation marks within the sentence.
import string
import re
valid_punctuation = string.punctuation.replace('-', '')
word_pattern = re.compile(r'([\w|-]+)([' + valid_punctuation + ']*)$')
# reverses word. ignores punctuation at the end.
# assumes a single word (i.e. no spaces)
def word_reverse(w):
m = re.match(word_pattern, w)
return ''.join(reversed(m.groups(1)[0])) + m.groups(1)[1]
def sentence_reverse(s):
return ' '.join([word_reverse(w) for w in re.split(r'\s+', s)])
str1 = raw_input('Enter the sentence: ')
print sentence_reverse(str1)

Simple solution without using re module:
print 'Enter the string:'
string = raw_input()
line = word = ''
for char in string:
if char.isalnum() or char == '-':
word = char + word
else:
if word:
line += word
word = ''
line += char
print line + word

you can do this.
print"Enter the string:"
str1=raw_input()
print( ' '.join(str1[::-1].split(' ')[::-1]) )
or then, this
print(' '.join([w[::-1] for w in a.split(' ') ]))

Related

Python String adjust

Hello is use some method like .isupper() in a loop, or string[i+1] to find my lower char but i don't know how to do that
input in function -> "ThisIsMyChar"
expected -> "This is my char"
I´ve done it with regex, could be done with less code but my intention is readable
import re
def split_by_upper(input_string):
pattern = r'[A-Z][a-z]*'
matches = re.findall(pattern, input_string)
if (matches):
output = matches[0]
for word in matches[1:]:
output += ' ' + word[0].lower() + word[1:]
return output
else:
return input_string
print(split_by_upper("ThisIsMyChar"))
>> split_by_upper() -> "This is my char"
You could use re.findall and str.lower:
>>> import re
>>> s = 'ThisIsMyChar'
>>> ' '.join(w.lower() if i >= 1 else w for i, w in enumerate(re.findall('.[^A-Z]*', s)))
'This is my char'
You should first try by yourself. If you didn't get it done, you can do something like this:
# to parse input string
def parse(str):
result= "" + str[0];
for i in range(1, len(str)):
ch = str[i]
if ch.isupper():
result += " ";
result += ch.lower();
return result;
# input string
str = "ThisIsMyChar";
print(parse(str))
First you need to run a for loop and check for Uppercase words then when you find it just add a space at the starting, lower the word and increment it to your new string. Simple, more code is explained in comments in the code itself.
def AddSpaceInTitleCaseString(string):
NewStr = ""
# Check for Uppercase string in the input string char-by-char.
for i in string:
# If it found one, add it to the NewStr variable with a space and lowering it's case.
if i.isupper(): NewStr += f" {i.lower()}"
# Else just add it as usual.
else: NewStr += i
# Before returning the NewStr, remove all the leading and trailing spaces from it.
# And as shown in your question I'm assuming that you want the first letter or your new sentence,
# to be in uppercase so just use 'capitalize' function for it.
return NewStr.strip().capitalize()
# Test.
MyStr = AddSpaceInTitleCaseString("ThisIsMyChar")
print(MyStr)
# Output: "This is my char"
Hope it helped :)
Here is a concise regex solution:
import re
capital_letter_pattern = re.compile(r'(?!^)[A-Z]')
def add_spaces(string):
return capital_letter_pattern.sub(lambda match: ' ' + match[0].lower(), string)
if __name__ == '__main__':
print(add_spaces('ThisIsMyChar'))
The pattern searches for capital letters ([A-Z]), and the (?!^) is negative lookahead that excludes the first character of the input ((?!foo) means "don't match foo, ^ is "start of line", so (?!^) is "don't match start of line").
The .sub(...) method of a pattern is usually used like pattern.sub('new text', 'my input string that I want changed'). You can also use a function in place of 'new text', in which case the function is called with the match object as an argument, and the value returned by the function is used as the replacement string.
The expression capital_letter_pattern.sub(lambda match: ' ' + match[0].lower(), string) replaces all matches (all capital letters except at the start of the line) using a lambda function to add a space before and make the letter lowercase. match[0] means "the entirety of the matched text", which in this case is the captial letter.
You can split it via Regex using r"(?<!^)(?=[A-Z])" pattern:
import re
txt = 'ThisIsMyChar'
c = re.compile(r"(?<!^)(?=[A-Z])")
first, *rest = map(str.lower, c.split(txt))
print(f'{first.title()} {" ".join(rest)}')
Pattern explanation:
(?<!^) checks to see if it is not at the beginning.
(?=[A-Z]) checks to see there a capital letter after it.
note These are non-capturing groups.

printing . before every character in a string

I have a string and it's "java is fun for sure" and i want to print
delete every vowel letters(aeiou)
print a "." before every character
so the out come would be like ".j.v. .s. .f.n. .f.r. .s.r"
I have tried this
s = str(input())
s.translate({ord(i): None for i in 'aeiou '})
the outcome is "jvsfnfrsr" but i don't know how to print "." before the letters.
Some help would be awesome! I'm sure this is a very simple issue, but for some reason i cannot come up with it!
Thx in advance! :)
import re
s = str(input())
s = s.translate({ord(i): None for i in 'aeiouAEIOU'})
print(re.sub('([^\s])', r'.\1', s))
Input: "java is fun for sure"
Output: ".j.v .s .f.n .f.r .s.r"
A solution using regex
You can use the 3-param version of maketrans to create the needed translation dictionary. Use the the sep param of print(..) to place the .:
s = "java is fun for sure"
s1 = s.translate(str.maketrans("", "", "aeiou")) # AEIOU are kept as is
print("", *s.translate(str.maketrans("", "", "aeiou")), sep=".")
or in short:
print("",*"java is fun for sure".translate(str.maketrans("", "", "aeiou")),sep=".")
The * before the string-var decomposes the string into its letters:
print(*"abc", sep = "#") # == print("a","b","c", sep = "#")
Output:
.j.v. .s. .f.n. .f.r. .s.r
If you need the resulting string you can use str.join():
s2 = '.' + '.'.join(s1)
What about this? It retains capitalised letters also.
vowels = 'aeiouAEIOU'
tmp = ''.join([char for char in str1 if char not in vowels])
final = ''.join(['.'+char for char in tmp])

Adding a space between string words

Write a function named string_processing that takes a list of
strings as input and returns an all-lowercase string with no
punctuation. There should be a space between each word. You do not
have to check for edge cases.
Here is my code:
import string
def string_processing(string_list):
str1 = ""
for word in string_list:
str1 += ''.join(x for x in word if x not in string.punctuation)
return str1
string_processing(['hello,', 'world!'])
string_processing(['test...', 'me....', 'please'])
My output:
'helloworld'
'testmeplease'
Expected output:
'hello world'
'test me please'
How to add a space in just between words?
You just need to keep all the words separate and then join them later with a space between them:
import string
def string_processing(string_list):
ret = []
for word in string_list:
ret.append(''.join(x for x in word if x not in string.punctuation))
return ' '.join(ret)
print(string_processing(['hello,', 'world!']))
print(string_processing(['test...', 'me....', 'please']))
Output:
hello world
test me please
Using regex, remove every non-letter and then join with a space:
import re
def string_processing(string_list):
return ' '.join(re.sub(r'[^a-zA-Z]', '', word) for word in string_list)
print(string_processing(['hello,', 'world!']))
print(string_processing(['test...', 'me....', 'please']))
Gives:
hello world
test me please
Try:
import string
def string_processing(string_list):
str1 = ""
for word in string_list:
st = ''.join(x for x in word if x not in string.punctuation)
str1 += f"{st} " #<-------- here
return str1.rstrip() #<------- here
string_processing(['hello,', 'world!'])
string_processing(['test...', 'me....', 'please'])
using regex:
import re
li = ['hello...,', 'world!']
st = " ".join(re.compile('\w+').findall("".join(li)))
The following code could help.
import string
def string_processing(string_list):
for i,word in enumerate(string_list):
string_list[i] = word.translate(str.maketrans('', '', string.punctuation)).lower()
str1 = " ".join(string_list)
return str1
string_processing(['hello,', 'world!'])
string_processing(['test...', 'me....', 'please'])
We can use the re library to process the words and add a space between them
import re
string = 'HelloWorld'
print(re.sub('([A-Z])', r' \1', string))
Output:
Hello World

Python iterations mischaracterizes string value

For this problem, I am given strings ThatAreLikeThis where there are no spaces between words and the 1st letter of each word is capitalized. My task is to lowercase each capital letter and add spaces between words. The following is my code. What I'm doing there is using a while loop nested inside a for-loop. I've turned the string into a list and check if the capital letter is the 1st letter or not. If so, all I do is make the letter lowercase and if it isn't the first letter, I do the same thing but insert a space before it.
def amendTheSentence(s):
s_list = list(s)
for i in range(len(s_list)):
while(s_list[i].isupper()):
if (i == 0):
s_list[i].lower()
else:
s_list.insert(i-1, " ")
s_list[i].lower()
return ''.join(s_list)
However, for the test case, this is the behavior:
Input: s: "CodesignalIsAwesome"
Output: undefined
Expected Output: "codesignal is awesome"
Console Output: Empty
You can use re.sub for this:
re.sub(r'(?<!\b)([A-Z])', ' \\1', s)
Code:
import re
def amendTheSentence(s):
return re.sub(r'(?<!\b)([A-Z])', ' \\1', s).lower()
On run:
>>> amendTheSentence('GoForPhone')
go for phone
Try this:
def amendTheSentence(s):
start = 0
string = ""
for i in range(1, len(s)):
if s[i].isupper():
string += (s[start:i] + " ")
start = i
string += s[start:]
return string.lower()
print(amendTheSentence("CodesignalIsAwesome"))
print(amendTheSentence("ThatAreLikeThis"))
Output:
codesignal is awesome
that are like this
def amendTheSentence(s):
new_sentence=''
for char in s:
if char.isupper():
new_sentence=new_sentence + ' ' + char.lower()
else:
new_sentence=new_sentence + char
return new_sentence
new_sentence=amendTheSentence("CodesignalIsAwesome")
print (new_sentence)
result is codesignal is awesome

Reverse each word in a string

I am having a small problem in my code. I am trying to reverse the words and the character of a string. For example "the dog ran" would become "ehT god nar"
The code almost works. It just does not add spaces. How would you do that?
def reverseEachWord(str):
reverseWord=""
list=str.split()
for word in list:
word=word[::-1]
reverseWord=reverseWord+word+""
return reverseWord
You are on the right track. The main issue is that "" is an empty string, not a space (and even if you fix this, you probably don't want a space after the final word).
Here is how you can do this more concisely:
>>> s='The dog ran'
>>> ' '.join(w[::-1] for w in s.split())
'ehT god nar'
def reversed_words(sequence):
return ' '.join(word[::-1] for word in sequence.split())
>>> s = "The dog ran"
>>> reversed_words(s)
... 'ehT god nar'
name=input('Enter first and last name:')
for n in name.split():
print(n[::-1],end=' ')
You can also deal with noise in the string using the re module:
>>> import re
>>> s = "The \n\tdog \t\nran"
>>> " ".join(w[::-1] for w in re.split(r"\s+", s))
'ehT god nar'
Or if you don't care:
>>> s = "The dog ran"
>>> re.sub(r"\w+", lambda w: w.group(0)[len(w.group(0))::-1], s)
'Teh god nar'
def reverse_words(sentence):
return " ".join((lambda x : [i[::-1] for i in x])(sentence.split(" ")))
Another way to go about it is by adding a space to your words reverseWord=reverseWord+word+" " and removing the space at the end of your output by using .strip()
def reverse_words(str):
reverseWord = ""
list = str.split()
for word in list:
word = word[::-1]
reverseWord = reverseWord + word + " "
return reverseWord.strip()
check out this post on how it's used
Here is a solution without using join / split :
def reverse(sentence):
answer = ''
temp = ''
for char in sentence:
if char != ' ':
temp += char
continue
rev = ''
for i in range(len(temp)):
rev += temp[len(temp)-i-1]
answer += rev + ' '
temp = ''
return answer + temp
reverse("This is a string to try")

Categories