Splitting strings in Python without split() - python

What are other ways to split a string without using the split() method? For example, how could ['This is a Sentence'] be split into ['This', 'is', 'a', 'Sentence'] without the use of the split() method?

sentence = 'This is a sentence'
split_value = []
tmp = ''
for c in sentence:
if c == ' ':
split_value.append(tmp)
tmp = ''
else:
tmp += c
if tmp:
split_value.append(tmp)

You can use regular expressions if you want:
>>> import re
>>> s = 'This is a Sentence'
>>> re.findall(r'\S+', s)
['This', 'is', 'a', 'Sentence']
The \S represents any character that isn't whitespace, and the + says to find one or more of those characters in a row. re.findall will create a list of all strings that match that pattern.
But, really, s.split() is the best way to do it.

A recursive version, breaking out the steps in detail:
def my_split(s, sep=' '):
s = s.lstrip(sep)
if sep in s:
pos = s.index(sep)
found = s[:pos]
remainder = my_split(s[pos+1:])
remainder.insert(0, found)
return remainder
else:
return [s]
print my_split("This is a sentence")
Or, the short, one-line form:
def my_split(s, sep=' '):
return [s[:s.index(sep)]] + my_split(s[s.index(sep)+1:]) if sep in s else [s]

Starting with a list of strings, if you would like to split these strings there are a couple ways to do so depending on what your desired output is.
Case 1: One list of strings (old_list) split into one new list of strings (new_list).
For example ['This is a Sentence', 'Also a sentence'] -> ['This', 'is', 'a', 'Sentence', 'Also', 'a', 'sentence'].
Steps:
Loop through the strings. for sentence in old_list:
Create a new string to keep track of the current word (word).
Loop through the characters in each of these strings. for ch in sentence:
If you come across the character(s) you want to split on (spaces in this example), check that word is not empty and add it to the new list, otherwise add the character to word.
Make sure to add word to the list after looping through all the characters.
The final code:
new_list = []
for sentence in old_list:
word = ''
for ch in sentence:
if ch == ' ' and word != '':
new_list.append(word)
word = ''
else:
word += ch
if word != '':
new_list.append(word)
This is equivalent to
new_list = []
for sentence in old_list:
new_list.extend(sentence.split(' '))
or even simpler
new_list = ' '.join(old_list).split(' ')
Case 2: One list of strings (old_list) split into a new list of lists of strings (new_list).
For example ['This is a Sentence', 'Also a sentence'] -> [['This', 'is', 'a', 'Sentence'], ['Also', 'a', 'sentence']].
Steps:
Loop through the strings. for sentence in old_list:
Create a new string to keep track of the current word (word) and a new list to keep track of the words in this string (sentence_list).
Loop through the characters in each of these strings. for ch in sentence:
If you come across the character(s) you want to split on (spaces in this example), check that word is not empty and add it to sentence_list, otherwise add the character to word.
Make sure to add word to sentence_list after looping through all the characters.
Append (not extend) sentence_list to the new list and move onto the next string.
The final code:
new_list = []
for sentence in old_list:
sentence_list = []
word = ''
for ch in sentence:
if ch == ' ' and word != '':
sentence_list.append(word)
word = ''
else:
word += ch
if word != '':
sentence_list.append(word)
new_list.append(sentence_list)
This is equivalent to
new_list = []
for sentence in old_list:
new_list.append(sentence.split(' '))
or using list comprehensions
new_list = [sentence.split(' ') for sentence in old_list]

This is simple code to split a char value from a string value; i.e
INPUT : UDDDUDUDU
s = [str(i) for i in input().strip()]
print(s)
OUTPUT: ['U','D','D','D','U','D','U','D','U']

sentence = 'This is a sentence'
word=""
for w in sentence :
if w.isalpha():
word=word+w
elif not w.isalpha():
print(word)
word=""
print(word)

string1 = 'bella ciao amigos'
split_list = []
tmp = ''
for s in string1:
if s == ' ':
split_list.append(tmp)
tmp = ''
else:
tmp += s
if tmp:
split_list.append(tmp)
print(split_list)
Output:
------> ['bella', 'ciao', 'amigos']
reverse_list = split_list[::-1]
print(reverse_list)
Output:
------> ['amigos', 'ciao', 'bella']

def mysplit(strng):
strng = strng.lstrip()
strng = strng.rstrip()
lst=[]
temp=''
for i in strng:
if i == ' ':
lst.append(temp)
temp = ''
else:
temp += i
if temp:
lst.append(temp)
return lst
print(mysplit("Hello World"))
print(mysplit(" "))
print(mysplit(" abc "))
print(mysplit(""))

This is one of the most accurate replicas of split method:
def splitter(x, y = ' '):
l = []
for i in range(x.count(y) + 1):
a = ''
for i in x:
if i == y: break
a += i
x = x[len(a) + 1 : len(x)]
l.append(a)
return ([i for i in l if i != ''])

my_str='This is a sentence'
split_value = []
tmp = ''
for i in my_str+' ':
if i == ' ':
split_value.append(tmp)
tmp = ''
else:
tmp += i
print(split_value)
Just a small modification to the code already given

Related

split string by all non alphabetic character occurences in Python

I'm trying to do the following function: We need to build a list out of a string. The list should only have alphabetical characters in it.
#if the input is the following string
mystring = "ashtray ol'god for, shure! i.have "
#the output should give a list like this:
mylist = ['ashtray','ol','god','for','shure','i','have']
No modules should be imported. I created the following function and it works, but I would be happy if someone could provide a better way to do it.
for ch in mystring:
if ch.isalpha() == False:
mystring = mystring.replace(ch,' ')
mylist = mystring.split()
by alphabetical character I mean all alphabetical characters present in UTF8, that means including arabic ,jewish chars etc.
Try this code
mystring = "ashtray ol'god for, shure! i.have "
lst = []
mystr = ''
for i in mystring:
temp = ord(i)
if (65 <= temp <= 90) or (97 <= temp <= 122):
mystr += i
else:
if mystr:
lst.append(mystr)
mystr = ''
print(lst)
Or
mystring = "ashtray ol'god for, shure! i.have "
lst = []
mystr = ''
for i in mystring:
if i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz':
mystr += i
else:
if mystr:
lst.append(mystr)
mystr = ''
print(lst)
Or (including Non-English characters)
mystring = "ashtray ol'god for, shure! i.have "
lst = []
mystr = ''
for i in mystring:
if i.isalpha():
mystr += i
else:
if mystr:
lst.append(mystr)
mystr = ''
print(lst)
Output:
['ashtray', 'ol', 'god', 'for', 'shure', 'i', 'have']
Tell me if its not working...

Not converting letters to uppercase and lowercase in python

I'm trying to make a program that will convert any text into a different form. That means that a text such as 'hi there' becomes 'hI tHeRe'.
list = []
word = input('Enter in a word or a sentence! ')
for num in range(len(word)):
list.clear()
list.append('i')
letter = word[num]
for x in range(len(list)):
if x % 2 == 0:
i = word.index(letter)
place = letter.lower()
word = word.replace(word[i], place)
if not x % 2 == 0:
i = word.index(letter)
place = letter.upper()
word = word.replace(word[i], place)
print(word)
However, when I run the code it just prints the same string as normal.
When using replace, you have to assign the result to your variable:
word = word.replace(word[i], place)
However, replace is actually not what you want here. replace replaces all instances of a certain pattern with a new string. In your current code, every instance of whatever letter word[i] represents will be replaced with the result of .lower() or .upper().
You also don't want to use the word list, since doing so will shadow the Python built-in list class.
If you want to keep most of your original logic, you can follow #khelwood's suggestion in the comments and end up with the following:
word = input('Enter in a word or a sentence! ')
wordList = list(word)
for i in range(len(word)):
if i % 2 == 0:
wordList[i] = word[i].lower()
else:
wordList[i] = word[i].upper()
print(''.join(wordList))
Here is one of my previous codes, you can change all the variable names to whatever you see fit.
s = input('Enter in a word or string.')
ret = ""
i = True # capitalize
for char in s:
if i:
ret += char.upper()
else:
ret += char.lower()
if char != ' ':
i = not i
print(ret)
I hope it works for you.
Try this one liner -
a = 'hi there'
''.join([i[1].lower() if i[0]%2==0 else i[1].upper() for i in enumerate(a)])
'hI ThErE'
If you care about each word starting from lowercase then this nested list comprehension works -
' '.join([''.join([j[1].lower() if j[0]%2==0 else j[1].upper() for j in enumerate(i)]) for i in a.split()])
'hI tHeRe'
The problem is with list.clear in the beginning of the for loop.
Each iteration you clear the list so the second for iteration run on the first item only.
Remove list.clear and it should scan the input word

How can I detect multiple items in a list that are separated with a somewhat equivalent list in Python?

I'm coding in python version 3, and I got a list with positive "words", but some items hold a space:
posWords = ['beautiful', 'love', 'happy day', 'enjoy', 'smelling flowers']
However, the text I need to analyse on positive words aren't holding any spaces within items:
wordList = ['I', 'enjoy', 'smelling', 'flowers', 'on', 'a', 'happy', 'day']
I want to iterate over wordList and when the algorithm sees words that are also in posWords, but merged (e.g. 'happy day'), remove the corresponding words in wordList ('happy', 'day') and add the merged version in wordList.
So in the end, the wordList must look like this:
wordList = ['I', 'enjoy', 'smelling flowers', 'on', 'a', 'happy day']
BIG UPDATE:
Because I promised you guys to keep you updated, this is my code so far. It was kinda tricky because in my lists with positive words and negative words there where phrases that contained max three words. So I needed to figure out how to work with that. I realised (also because of the answers you guys gave me, thanks again!) that I had to make lists from all the words of the text that needed to be analysed with either 3, 2, or 1 words in one string item so I can check if the items also appear in my lists of positive words end negative words. Here is my code so far. It's kinda bulky, with a lot of copy pasting... Im planning to fix that but im quite tired and weekend is starting now, so no hate please! (tips are welcome tho)
from textblob import TextBlob
# open the files with negative words
negatives = open("neg_dutch_2.txt")
neg_list = []
# push all the words from text file to list
for lines in negatives:
lines = lines.lower()
neg_list.append(lines.strip("\n"))
neg_no_space = []
neg_one_space = []
neg_two_spaces = []
neg_three_spaces = []
count = 0
def neg_how_many_spaces(neg_list, neg_no_space, neg_one_space, neg_two_spaces,
neg_three_spaces, count):
# read every word in the list with negative words
for i in range(len(neg_list)):
# every word is a phrase, because there are "words" with spaces
phrase = neg_list[i]
# look at every character and assign the phrase to a list
# that correspondes with the number of spaces in it
for j in range(len(phrase)):
if phrase[j] == " ":
count += 1
if phrase[-1]:
if count == 1:
neg_one_space.append(phrase)
elif count == 2:
neg_two_spaces.append(phrase)
elif count == 3:
neg_three_spaces.append(phrase)
else:
neg_no_space.append(phrase)
# reset the counter to avoid the total sum of spaces in a list
count = 0
return neg_list, neg_no_space, neg_one_space, neg_two_spaces,
neg_three_spaces, count
neg_how_many_spaces(neg_list, neg_no_space, neg_one_space,
neg_two_spaces, neg_three_spaces, count)
# open the files with positive words
positives = open("pos_dutch_2.txt")
pos_list = []
# push all the words from text file to list
for lines in positives:
lines = lines.lower()
pos_list.append(lines.strip("\n"))
pos_no_space = []
pos_one_space = []
pos_two_spaces = []
pos_three_spaces = []
count = 0
def pos_how_many_spaces(pos_list, pos_no_space, pos_one_space, pos_two_spaces,
pos_three_spaces, count):
# read every word in the list with positive words
for i in range(len(pos_list)):
# every word is a phrase, because there are "words" with spaces
phrase = pos_list[i]
# look at every character and assign the phrase to a list
# that correspondes with the number of spaces in it
for j in range(len(phrase)):
if phrase[j] == " ":
count += 1
if phrase[-1]:
if count == 1:
pos_one_space.append(phrase)
elif count == 2:
pos_two_spaces.append(phrase)
elif count == 3:
pos_three_spaces.append(phrase)
else:
pos_no_space.append(phrase)
# reset the counter to avoid the total sum of spaces in a list
count = 0
return pos_list, pos_no_space, pos_one_space, pos_two_spaces,
pos_three_spaces, count
pos_how_many_spaces(pos_list, pos_no_space, pos_one_space,
pos_two_spaces, pos_three_spaces, count)
text = open("nrc_sample.TXT")
# reading the article, using TextBlob library to seperate each word
text = text.read()
blob = TextBlob(text)
# these are words that are bound to the meta-deta of the articlesfile
ruis = ["DOCUMENTS", "SECTION", "LENGTH", "LOAD-DATE", "LANGUAGE",
"PUBLICATION-TYPE", "JOURNAL-CODE", "BYLINE", "All", "Rights",
"Reserved", "Copyright", "krant", "Krant", "KRANT", "blz"]
# make a list for all the words in the articles
word_list = []
# and store every word in that list
for word in blob.words:
if not any(x in word for x in ruis):
word = word.lower()
if word.isalpha():
word_list.append(word)
# variables for the frequencies of negative and positive words in articles
amount_pos = 0
amount_neg = 0
count = 0
phrases_four = []
phrases_three = []
phrases_two = []
phrases_one = []
amount_neg = 0
# PHRASE 4
for i in range(0, len(word_list)-4, 1):
if word_list[-1]:
phrase = " "
strings = word_list[i], word_list[i+1], word_list[i+2], word_list[i+3]
phrase = phrase.join(strings)
phrases_four.append(phrase)
count = 0
for phrase in phrases_four:
print("phrase4", count, phrase)
count += 1
for neg in neg_three_spaces:
if phrase == neg:
print("negatief woord^")
amount_neg += 1
print(amount_neg)
# PHRASE 3
for i in range(0, len(word_list)-3, 1):
if word_list[-1]:
phrase = " "
strings = word_list[i], word_list[i+1], word_list[i+2]
phrase = phrase.join(strings)
phrases_three.append(phrase)
count = 0
for phrase in phrases_three:
print("phrase3", count, phrase)
count += 1
for neg in neg_two_spaces:
if phrase == neg:
print("negatief woord^")
amount_neg += 1
print(amount_neg)
# PHRASE 2
# start at index zero, till one before end of the list
for i in range(0, len(word_list)-2, 1):
# until it hits the last word of the list, make for every two words in the
# article next to each other a phrase of two words, so we can check if
# there are phrases in the article who also exists in the pos or neg wordslists
if word_list[-1]:
phrase = " "
strings = word_list[i], word_list[i+1]
phrase = phrase.join(strings)
phrases_two.append(phrase)
count = 0
# examine each phrase, and check if the same phrase exists in the list
# with negative phrases containing two words
# dont forget to delete the counter, is only for readability
for phrase in phrases_two:
count += 1
for neg in neg_one_space:
if phrase == neg:
amount_neg += 1
print(amount_neg)
# JUST A WORD
for i in range(0, len(word_list)-1, 1):
if word_list[-1]:
phrase = word_list[i]
phrases_one.append(phrase)
count = 0
for phrase in phrases_one:
print("phrase1", count, phrase)
count += 1
for neg in neg_no_space:
if phrase == neg:
print("negatief woord^")
amount_neg += 1
print(amount_neg)
Here is a way to do it:
posWords = ['beautiful', 'love', 'happy day', 'enjoy','smelling flowers']
wordList = ['I', 'enjoy', 'smelling', 'flowers', 'on', 'a', 'happy', 'day']
# Create a sentence for the wordList.
joinedWordList = " ".join(wordList)
# Find all phrases in the posWords list.
phrases = [elem for elem in posWords if len(elem.split()) > 1]
# For every phrase, locate it in the sentence,
# count the space characters which is the same number as the index of the first word of phrase in the word list,
# insert the phrase and delete the word that combine the phrase from the wordList.
for phrase in phrases:
try:
i = joinedWordList.index(phrase)
spaces = len([letter for letter in joinedWordList[:i] if letter==' '])
wordList.insert(spaces,phrase)
del wordList[spaces+1:spaces+1 + len(phrase.split())]
except ValueError:
pass
print(wordList)
Output:
['I', 'enjoy', 'smelling flowers', 'on', 'a', 'happy day']
Here is another approach that would work for any phrase length:
posWords = ['beautiful', 'love', 'happy day', 'enjoy','smelling flowers']
wordList = ['I', 'enjoy', 'smelling', 'flowers', 'on', 'a', 'happy', 'day']
for w in posWords:
nrWords = len(w.split(' '))
if nrWords > 1:
word_array = w.split(' ')
word_index_array = [wordList.index(w) for w in word_array]
index_difference_array = [abs(b-a) for a in word_index_array[0:-1] for b in word_index_array[1:]]
if sum(index_difference_array) == len(index_difference_array): #elements are consecutive in wordList
for elem in word_array:
wordList.remove(elem)
wordList.insert(word_index_array[0], w)
Output will be:
['I', 'enjoy', 'smelling flowers', 'on', 'a', 'happy day']
But if we for example input something like:
posWords = ['beautiful', 'love', 'happy day', 'enjoy','smelling flowers on']
wordList = ['I', 'enjoy', 'smelling', 'flowers', 'on', 'a', 'happy', 'day']
The output will be:
['I', 'enjoy', 'smelling flowers on', 'a', 'happy day']
Another way to do it:
>>> m=["good bad", "enjoy", "play"]
>>> l=["good", "bad", "happy", "delight"]
>>>
>>> for e in m:
... tmp = e.split(" ")
... if(len(tmp) > 1):
... l = [ent for ent in l if ent not in tmp]
... l.append(" ".join(tmp))
...
>>>
>>> l
['happy', 'delight', 'good bad']

How to make a function to find duplicacy in a character string?

Here is the code I have written to find duplicate characters and then replace them by ')' and original characters by '(' in a string and it should ignore capitalization.
def duplicate_finder(word):
word1 = word.lower();
w = list(word1);
w1 = '';
for i in range(0, len(word1)):
if ([v in word1.replace(w[i], '') for v in w[i]]==[True]):
w1 += ')';
else:
w1 += '(';
return (w1)
But this function always returns me '((((((...((' [till the number of characters in the input string]. Can someone please point me the fault in my code!!!
Thanks in advance.
The loop you run always gives False because: word1.replace(w[i],'') replaces all instances of w[i] in word1. So when you look for v in word1.replace(w[i],''), it doesn't find any as you relaced all of them. This calls w1 += '(' everytime!
You can do :
>>> def duplicate_finder(word):
... word1 = word.lower();
... w = list(word1);
... w1 = '';
... for i in range(0, len(word1)):
... if ([v in word1[:i]+word1[i+1:] for v in w[i]]==[True]):
... w1 += ')';
... else:
... w1 += '(';
... return (w1)
...
>>> duplicate_finder('hello')
'(())('
I would do it some other way, involving dictionary keeping counts to get true O(n) algo
Here's one way (assuming I understand the question):
def duplicate_finder(word):
word1 = word.lower();
for c in word1:
# If more that one occurence of c
if 1 != word1.count(c):
# Replace all c with (
word1 = word1.replace(c, '(')
# Only one occurence
else:
word1 = word1.replace(c, ')')
return word1
def duplicate_finder(word):
word = word.lower()
l = len(word)
for i in range(l):
index = word.find(word[i], i+1)
if index != -1 and word[i] !=')':
word = word.replace(word[i], '(', 1)
word = word.replace(word[index], ')', 1)
return (word)
Test:
I gave input as "Sanjana"
Output screenshot with steps of replacement
It resulted in s((j))a
Note:
word[i] != ')' check is necessary as there is a possibility of replacement of already existing ) in the unseen segment of the string, and thus can produce weird output
Edit
def duplicate_finder(word):
word = word.lower()
l = len(word)
for i in range(l):
index = word.find(word[i], i+1)
if word[i] not in [')', '('] :
if index != -1:
word = word.replace(word[i], ')')
else:
word = word.replace(word[i], '(')
return (word)
def duplicate_finder(word):
word1 = word.lower();
w1 = '';
length = len(word1)
for i in range(0, length):
w2 = word1[i]
if(word1[i] != ")"):
word1 = word1.replace(word1[i],"(",1)
for v in range(i+1,length):
if(word1[v] != ")" and word1[v] != "("):
if (word1[v] == w2):
word1 = word1.replace(w2,")")
return (word1)
Here is a possible solution:
def duplicate_finder(word):
word1 = word.lower()
w1 = ''
found_chars= set([])
for c in word1:
if c in found_chars:
w1+=')'
else:
found_chars.add(c)
w1+='('
print w1
#Satya, I have used the concept of Counter container of collections module in Python to solve your problem.
A Counter is a subclass of dict. Therefore it is an unordered collection where elements and their respective count are stored as dictionary. This is equivalent to bag or multiset of other languages.
Note: Do not forget to check the References for Counter which is give at very bottom of this answer and comment if find any difficulty.
Have a look at the below code.
"""
StkOvrFlw link: https://stackoverflow.com/questions/50485559/how-to-make-a-function-to-find-duplicacy-in-a-character-string
Aim: [
'1. Here, original character means the character which '
'is first time appearing in the string'
'2. Replacing original character with => ('
'3. If there are more occurences of original character'
then replace them with => )'
]
References: http://www.pythonforbeginners.com/collection/python-collections-counter
"""
from collections import Counter
# Code
def duplicate_finder(word):
word = word.lower()
i = 1;
for ch, count in Counter(word).items():
# print '(', i, ') Original character: \'', ch, '\'with', count - 1, 'more occurence(s)'
if count == 1:
word = word.replace(ch, '(') # Only 1 occurence of original character
else:
l = list(word)
l[word.find(ch)] = '(' # Replace original character with (
word = ''.join(l)
word = word.replace(ch, ')') # Replace other occurences of original character with )
# print 1, 'occurence of \'', ch, '\' replaced with \'(\' and remaining ', count - 1, ' occurence(s) with \')\''
# print 'Iteration ', i, ' gives: ', word, '\n'
i += 1
return word
# Test case 1
print "I/P: abaccccsgfsyetgdggdh"
print "O/P: ", duplicate_finder('abaccccsgfsyetgdggdh')
"""
I/P: abaccccsgfsyetgdggdh
O/P: (()()))((()((()()))(
"""
# Test case 2
print "\nI/P: AAABBBCCC34519543absd67das1729"
print "O/P: ", duplicate_finder('AAABBBCCC34519543absd67das1729')
"""
I/P: AAABBBCCC34519543absd67das1729
O/p: ())())())((((()))))(((()))))()
"""
References: You can find nice articles on Counter container of Python at:
http://www.pythonforbeginners.com/collection/python-collections-counter and
https://www.geeksforgeeks.org/counters-in-python-set-1/
# Find duplicate characters in a string by following conditions:
# - the first (original) character will replaced by '('
# - all others matches will replaced by ')'
# - all in a string with ignore capitalization
def duplicate_finder(word):
s = word.lower()
for ch in s:
if s.count(ch) > 1: # is there more copies of this one character ?
s = s.replace(ch, '(', 1).replace(ch, ')') # the first match will replaced by '(' character, and then all other matches will replaced by ')' character
return s
print 'result: ' + duplicate_finder('hello world') # result: he()( w)r)d
# 0123456789A 0123456789A
New code (by comment from Satya - at 23:26):
# Find duplicate characters in the string by following conditions:
# - all single characters will replaced by '('
# - all multiple characters (duplicates) will replaced by ')'
# - input string must ignore capitalization
def duplicate_finder(word):
s = word.lower()
for ch in s:
if s.count(ch) > 1: # is there more copies of this one character ?
s = s.replace(ch, ')' ) # replace all matched ch by ')'
else:
s = s.replace(ch, '(', 1) # replace this one matched ch by '(' - there's only one character
return s
print 'result: ' + duplicate_finder('hello world') # result: (()))(()()(
# 0123456789A 0123456789A

How to preserve and reverse a string?

Write a function that accepts a string of words separated by spaces
consisting of alphabetic characters and returns a string such that
each word in the input string is reversed while the order of the words
in the input string is preserved. Capitalization does matter here. The
length of the input string must be equal to the length of the output
string i.e. there should be no trailing or leading spaces in your
output string. For example if:
input_string = “this is a sample test”
then the function should return a string such as:
"siht si a elpmas tset"
This is my code:
def preserve_and_reverse (input_str):
list = input_str.split()
print (list)
reverse_character = ""
for i in range (0, len(input_str)):
split_list = list[0:(i + 1)]
print (split_list)
for j in split_list_advance:
reverse_character = reverse_character + split_list[j]
output_str = output_str.append(reverse_character)
output = output_str.replace("", " ")
print (output)
#Main Program
input_str = input("Enter a string: ")
result = preserve_and_reverse (input_str)
print (result)
I am not getting anywhere with the code. Should I try a different approach like traverse each character and when I encounter a white-space just slice the string and then perform a reverse?
Any help would be appreciated.
Split over spaces, reverse each string through map with [::-1] then join them back with ' '.join
>>> s = 'this is a sample test'
>>>
>>> ' '.join(map(lambda s:s[::-1], s.split()))
'siht si a elpmas tset'
This is how I would have done it:
def preserve_and_reverse(input_str):
# Split the String into an Array
list_ = input_str.split(" ")
return_str = ""
# For Each String in the Array
for item in list_:
# Add Reversed String to Return String
return_str += item[::-1] + " "
# Return String without leading/trailing spaces
return return_str.strip()
# Main Program
string_input = input("Enter a string: ")
result = preserve_and_reverse(string_input.strip())
print(result)
Something like this will do (step-by-step):
input_string = "this is a sample test"
words = input_string.split()
nwords = []
for i in words:
rword = ""
for c in reversed(word):
rword += c
nwords.append(rword)
output_string = " ".join(nwords)
print(output_string)
Result:
siht si a elpmas tset
Step by step explanation:
You split your input text into list of string:
words = input_string.split()
You iterate over the words
for word in words):
For each word, you prepare a reversed word rword and build up the reversed word by adding up character from the old word but reversed:
rword = ""
for c in reversed(word):
rword += c
nwords.append(rword)
you rejoin the reversed words - but in order and print it:
output_string = " ".join(nwords)
print(output_string)
Or, more simply:
input_string = "this is a sample test"
words = input_string.split()
output_string = ""
for word in words:
for c in reversed(word):
output_string += c
output_string += " "
print(output_string)
word[::-1] reverses the order of the string variable named word which is obtained by iterating through each split word in the sentence.
>>> ' '.join(word[::-1] for word in input_string.split())
'siht si a elpmas tset'
Step by step:
>>> input_string.split()
['this', 'is', 'a', 'sample', 'test']
>>> [word[::-1] for word in input_string.split()]
['siht', 'si', 'a', 'elpmas', 'tset']
>>> ' '.join(word[::-1] for word in input_string.split())
'siht si a elpmas tset'
All of the other answers so far ignore what happens when extra spaces are between words or at either end of the input string. Please test your code to verify that is works properly. The main function provided below has a few tests that you may want to use to verify your function is working properly, and you may want to add more tests if you find that your code is not behaving correctly:
def main():
print('Running test 1 ...')
text = 'this is a sample test'
par = preserve_and_reverse(text)
assert par == 'siht si a elpmas tset'
print('Running test 2 ...')
text = 'This is a sample TEST'
par = preserve_and_reverse(text)
assert par == 'sihT si a elpmas TSET'
print('Running test 3 ...')
text = 'This string has some extra spaces'
par = preserve_and_reverse(text)
assert par == 'sihT gnirts sah emos artxe secaps'
print('Running test 4 ...')
text = ' check spaces at string ends '
par = preserve_and_reverse(text)
assert par == ' kcehc secaps ta gnirts sdne '
print('Done!')
def preserve_and_reverse(text):
return ' '.join(word[::-1] for word in text.split(' '))
if __name__ == '__main__':
main()
def sample(string):
list=[]
string1=string.split()
for i in string1:
list.append(i[::-1])
print(" ".join(list))
if __name__=="__main__":
input=input("Enter string: ")
sample(input)

Categories