This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed 2 years ago.
I am working on a script that takes the user input and reverses the whole input.
for example if the user inputs "London" it will be printed as "nodnol" . I am currently being able to reverse the order of a certain number of letters but not being able to reverse the entire string .
You can reverse it with the slicing syntax:
s = input("Enter a string: ")
print s[::-1]
Enter a string: London
nodnoL
print raw_input().lower()[::-1]
I'm under the impression that you cannot use any of the nice things that make Python a soo nice language, so here it is my low-key answer...
At the beginning, we have a string,
>>> ast = input('Tell me a word of your choice: ') # <--- "London"
We can compute its length using the len builtin
>>> last = len(ast) # <--- 6
now we want to index the string in reverse, the string indices are 0 ... 5 so we need the sequence 5 4 3 2 1 0
>>> for i in range(last): print(last-1-i)
5
4
3
2
1
0
Let's see that we can access the characters of the string in reverse using the indexing scheme above
>>> for i in range(last): print(ast[last-1-i])
n
o
d
n
o
L
Finally, we have to build the reversed string, using the + operator and starting from the null string
>>> rast = ""
>>> for i in range(last): rast += ast[last-1-i]
>>> print(rast)
nodnoL
>>>
To summarize
ast = input('Tell me a word of your choice: ')
last = len(ast)
rast = ""
for i in range(last):
rast += ast[last-1-i]
s = input("Enter a string: ")
s = s.lower()
print s[::-1]
string=input('Enter String: ')
print (string[::-1])
string: heaven
output:nevaeh
Using extended slice syntax: 'string_goes_here'[::-1]
Example : print('london'[::-1])
Online Compiler link
Extended Slices :
Ever since Python 1.4, the slicing syntax has supported an optional
third step'' orstride'' argument. For example, these are all
legal Python syntax: L[1:10:2], L[:-1:1], L[::-1]. This was added to
Python at the request of the developers of Numerical Python, which
uses the third argument extensively. However, Python's built-in list,
tuple, and string sequence types have never supported this feature,
raising a TypeError if you tried it. Michael Hudson contributed a
patch to fix this shortcoming.
--Reference
Related
This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 2 years ago.
I am currently doing a task but I am stuck at the moment, so here is the code so far I have written:
string = input('please enter a string: ')
s = []
def sentenceCapitalize(string):
strn = string.split('. ') #convert to a list
for x in strn:
y = x[0].upper()
y += x[1:].lower()
s.append(y)
print('.'.join(s))
sentenceCapitalize(string)
It only gets me the result as a list and period is disappeared
Unexpected Output:
Expected Output:
Hello. My name is Joe. What is your name?
And here is the question from the book:
Write a program with a function that accepts a string as an argument
and returns a copy of the string with the first character of each
sentence capitalized. For instance, if the argument is “hello. my name
is Joe. what is your name?” the function should return the string
“Hello. My name is Joe. What is your name?” The program should let the
user enter a string and then pass it to the function. The modified
string should be displayed.
Can you fix this solution? thanks.
The main three errors you have in your code are:
You convert to lower case the rest of the sentence, so for example Joe will become joe
You split based on ('. '), but when concatenating back you join by ('.'), so you are missing the white space
You need a regex split, to consider both , and .. In the regex you pass the two options separated by |, and for the case of dot you need to add before '' since '.' itself is an operator in regex. More about Regular Expression
Try this:
string = input('please enter a string: ')
s = []
import re
def sentenceCapitalize(string):
strn = re.split(',|\.', string) #convert to a list
for x in strn:
y = x[0].upper()
y += x[1:]
s.append(y)
print('.'.join(s))
sentenceCapitalize(string)
One sentence solution:
print('. '.join([st[0].upper() + st[1:] for st in string.split('. ')]))
This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed 2 years ago.
I am trying to create a program in which the user inputs a statement containing two '!' surrounding a string. (example: hello all! this is a test! bye.) I am to grab the string within the two exclamation points, and print it in reverse letter by letter. I have been able to find the start and endpoints that contain the statement, however I am having difficulties creating an index that would cycle through my variable userstring in reverse and print.
test = input('Enter a string with two "!" surrounding portion of the string:')
expoint = test.find('!')
#print (expoint)
twoexpoint = test.find('!', expoint+1)
#print (twoexpoint)
userstring = test[expoint+1 : twoexpoint]
#print(userstring)
number = 0
while number < len(userstring) :
letter = [twoexpoint - 1]
print (letter)
number += 1
twoexpoint - 1 is the last index of the string you need relative to the input string. So what you need is to start from that index and reduce. In your while loop:
letter = test[twoexpoint- number - 1]
Each iteration you increase number which will reduce the index and reverse the string.
But this way you don't actually use the userstring you already found (except for the length...). Instead of caring for indexes, just reverse the userstring:
for letter in userstring[::-1]:
print(letter)
Explanation we use regex to find the pattern
then we loop for every occurance and we replace the occurance with the reversed string. We can reverse string in python with mystring[::-1] (works for lists too)
Python re documentation Very usefull and you will need it all the time down the coder road :). happy coding!
Very usefull article Check it out!
import re # I recommend using regex
def reverse_string(a):
matches = re.findall(r'\!(.*?)\!', a)
for match in matches:
print("Match found", match)
print("Match reversed", match[::-1])
for i in match[::-1]:
print(i)
In [3]: reverse_string('test test !test! !123asd!')
Match found test
Match reversed tset
t
s
e
t
Match found 123asd
Match reversed dsa321
d
s
a
3
2
1
You're overcomplicating it. Don't bother with an index, simply use reversed() on userstring to cycle through the characters themselves:
userstring = test[expoint+1:twoexpoint]
for letter in reversed(userstring):
print(letter)
Or use a reversed slice:
userstring = test[twoexpoint-1:expoint:-1]
for letter in userstring:
print(letter)
This question already has answers here:
What is the difference between re.search and re.match?
(9 answers)
Closed 3 years ago.
I have this string:
field = 1400 x 3524
I want to take these numbers into two seperate variables so I can perform multiplication. This is how I do it:
num1 = re.match("(\d{3,4})(?= x)", field).group(1)
num2 = re.match("(?<=x )(\d{3,4})", field).group(1)
I works with the first number, but the second number comes out as a NoneType.
What am I doing wrong?
Try this:
>>> import re
>>> a = 'field = 1400 x 3524'
>>> m = re.findall( r'\d+', a )
>>> m
['1400', '3524']
>>>
re module documentation states that:
Note that patterns which start with positive lookbehind assertions
will not match at the beginning of the string being searched; you will
most likely want to use the search() function rather than the match()
function
In your case that means you should do:
import re
field = "1400 x 3524"
num2 = re.search("(?<=x )(\d{3,4})", field).group(0)
print(num2) # 3524
Note that here beyond changing match to search I also changed group(1) to group(0)
This question already has answers here:
Python replace string pattern with output of function
(4 answers)
Closed 5 years ago.
Say I have the following string:
mystr = "6374696f6e20????28??????2c??2c????29"
And I want to replace every sequence of "??" with its length\2. So for the example above, I want to get the following result:
mystr = "6374696f6e2022832c12c229"
Meaning:
???? replaced with 2
?????? replaced with 3
?? replaced with 1
???? replaced with 2
I tried the following but I'm not sure it's the good approach, and anyway -- it doesn't work:
regex = re.compile('(\?+)')
matches = regex.findall(mystr)
if matches:
for match in matches:
match_length = len(match)/2
if (match_length > 0):
mystr= regex .sub(match_length , mystr)
You can use a callback function in Python's re.sub. FYI lambda expressions are shorthand to create anonymous functions.
See code in use here
import re
mystr = "6374696f6e20????28??????2c??2c????29"
regex = re.compile(r"\?+")
print(re.sub(regex, lambda m: str(int(len(m.group())/2)), mystr))
There seems to be uncertainty about what should happen in the case of ???. The above code will result in 1 since it converts to int. Without int conversion the result would be 1.0. If you want to ??? to become 1? you can use the pattern (?:\?{2})+ instead.
This question already has answers here:
Check if a string contains a number
(20 answers)
Closed 7 years ago.
I am a newbie in Python. I am making a program where I take a input from user and check if any number is inside in the string. I am checking it by taking it in a variable. Is it not correct to check via a VARIABLE?
user_string=input("Enter the Word:")
print (user_string)
for index in (0,9):
number=str(index) #Typecasting Int to String
if number in user_string: #Check if Number exist in the string
print ("yes")
output:
Enter the Word:helo2
helo2
You can use the string method isdigit() on each character in a generator expression within any. This will short-circuit upon finding the first numeric character (if one is present)
>>> user_string = 'helo2'
>>> any(i.isdigit() for i in user_string)
True
>>> user_string = 'hello'
>>> any(i.isdigit() for i in user_string)
False
Look at your for-loop. You are looping over a tuple (0,9). So actually you are only testing for 0 and 9. Use range(10) instead.
More elegant, to get the numbers inside your string, you can use sets:
import string
print 'yes' if set(string.digits).intersection(user_string) else 'no'