I just start learning python, and would like to ask the reader to input a number,but i would like to skip comma and space that reader input.
a = input("input a number:")
x = y
print(dec(x))
However, if i use split, it would become a list or 2 number
for example, when user input 12,3456,
and y would become ['12', '3456']
And my expected output is 123456 as a integer but not a list with two values.
I tried to use replace before, but it said
"TypeError: object of type 'int' has no len()"
Instead of using split, you can just use replace to remove any comma or space from the string you read from input.
a=input("input a number:")
a = a.replace(",","").replace(" ","")
print(a)
You could try something like this.
>>> number = int("".join(input().split(',')))
12,3456
>>> number
123456
>>>
Basically just splitting the input based on ',' and then joining them
You could also try replacing the ',' with ''
>>> number = int(input().replace(',',''))
12,3456
>>> number
123456
>>>
Hope this helps!
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('. ')]))
I'm trying to iterate over a string and get all the numbers so that I can add them to a list, which I need for another task. I have multiple functions that recurrsively refer to each other and the original input is a list of data. The problem is that when I print the string I get the right output, but if I iterate over it and print all the indexes I get seperate digits, so 1,1 instead of 11 or 9,3 instead of 93. Does anyone have a simple solution to this problem? I'm not Quite experienced in programming so it may seem like a simple task but I can't figure it out at the moment. Here's my code for the problem part.
numbers = names.split('\t')[1].split(' ')[1]
print numbers
some of the output:
8
44
46
86
now if I use the following code:
numbers = names.split('\t')[1].split(' ')[1]
for i in numbers:
print i
I get the following output:
8
4
4
4
6
8
6
or when I convert to a list:
numbers = names.split('\t')[1].split(' ')[1]
print list(numbers)
output:
['8']
['4', '4']
['4', '6']
['8', '6']
The input names is structured in the following way: Andy Gray\t 2807 53
where I have many more names, but they are all structured like this.
I then split by \t to remove the names and then split again by ' ' to get the numbers. I then have 2 numbers and take the second index to get the numbers I want, which are the second numbers next to the name.
My only goal for now is to get the 'complete' digits, so the output as it is like when I print it. I need to be able to get a list of those numbers as integers where every index is the complete digit, so [8,44,46,86] etc. I can then iterate over the numbers and use them. Once I can do that I know what to do, but I'm stuck at this point for now. Any help would be nice.
Link to complete input and python code I am using, in case it makes things more clear:
Demo
str.rsplit()
works like str.split(), but starts from the right end.
s = "Andy Gray\t 2807 53"
_, number = s.rsplit(maxsplit=1)
print(number)
If you know that all your input is structured the same way and you have the guarantee that the string ends with the 2 digits of your interest, why don't just do the following?
names_list = ['Andy gray\t2807 53', 'name surname\t2807 934']
for n in names_list:
print (n[-2:])
On the other hand if you're not sure the last number only contains 2 digits, all the splitting on tab is unnecessary:
import re
names_list = ['Andy gray\t2807 53', 'name surname\t2807 94']
for n in names_list:
try:
if re.compile(r'.*\d+$').match(n) and ' ' in n:
print(n.split()[-1])
except:
pass
EDIT after reading the code added by OP
The code looks good, but the problem is that my input(names) is not a list of strings. I have a string like this: Guillaume van Steen 5855 5 Sven Silvis Cividjian 1539 88 Jan Willem Swarttouw 3911 66 which goes in further. This is why I split at the tab and whitespace to get the final number.
Maybe this code help:
from pathlib import Path
file = Path('text.txt')
text = file.read_text()
Here is were split the file in lines:
lines = text.split('\n')
So can use the function with a little added check
def get_numbers(list_of_strings):
numbers = list()
for string in list_of_strings:
# here check if the line has a "\t" so asume is a valid line
if '\t' in string:
numbers.append(int(string.split()[-1]))
return numbers
numbers = get_numbers(lines)
print(numbers)
You can split the string by whitespaces again and convert each value to int.
For example,
numbers = names.split('\t')[1].split(' ')[1]
list_numbers = [int(x) for x in numbers.split(' ')]
Then you will have your list of 'complete' digits
I'm trying to put multiple interest rates from one input into a list. I'm assuming just putting a comma between them wont separate them into different variables in the list? Is there a way I can get them all into a list in one input or do i need to run the input multiple times and add one each time?
interest_rates_list = []
while True:
investment = input("Please enter the amount to be invested ")
periods = input("Please enter the number of periods for investment maturity ")
if int(periods) < 0:
break
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list.append(interest_rates)
If you input is something like:
4 5 12 8 42
then you can simply split it up by space and assign to values list:
values = input().split()
If your input something like 4,5,12, then you need to use split(',').
You can split the input string into several string and then convert it to float. This can be done in one line.
interest_rates = list(map(float, interest_rates.split(",")))
Here I go a step further, your next move will be to calculate some return based on interest rates, and so you will need float/integer to do so.
The python string function split can accept a delimiter character and split the input string into a list of values delimited by that character.
interest_rates = input("Please enter the interest rate for each period ")
interest_rates_list = interest_rates.split(",")
If you take the input, you can convert it to a string by using:
str(interest_rates)
Let this be variable A
So, A = str(interest_rates)
Now, to seperate each entry of the interest rates, we do:
interest_rates_list = A.split(' ')
This function literally splits the string at all spaces and returns a list of all the broken pieces.
NOTE: if you do A.split(*any string or character*) it'll split at the mentioned character. Could be ',' or ';' or ':', etc.
Now you can iter over the newly formed list and convert all the numbers stored as string to ints or floats by doing
for i in interest _rates_list:
i = float(i) #or int(i) based on your requirement
I have a string 'A1T1730'
From this I need to extract the second letter and the last four letters. For example, from 'A1T1730' I need to extract '1' and '1730'. I'm not sure how to do this in Python.
I have the following right now which extracts every character from the string separately so can someone please help me update it as per the above need.
list = ['A1T1730']
for letter in list[0]:
print letter
Which gives me the result of A, 1, T, 1, 7, 3, 0
my_string = "A1T1730"
my_string = my_string[1] + my_string[-4:]
print my_string
Output
11730
If you want to extract them to different variables, you can just do
first, last = my_string[1], my_string[-4:]
print first, last
Output
1 1730
Using filter with str.isdigit (as unbound method form):
>>> filter(str.isdigit, 'A1T1730')
'11730'
>>> ''.join(filter(str.isdigit, 'A1T1730')) # In Python 3.x
'11730'
If you want to get numbers separated, use regular expression (See re.findall):
>>> import re
>>> re.findall(r'\d+', 'A1T1730')
['1', '1730']
Use thefourtheye's solution if the positions of digits are fixed.
BTW, don't use list as a variable name. It shadows builtin list function.
Well you could do like this
_2nd = lsit[0][1]
# last 4 characters
numbers = list[0][-4:]
You can use the function isdigit(). If that character is a digit it returns true and otherwise returns false:
list = ['A1T1730']
for letter in list[0]:
if letter.isdigit() == True:
print letter, #The coma is used for print in the same line
I hope this useful.
I am trying to print the last part of a string before a certain character.
I'm not quite sure whether to use the string .split() method or string slicing or maybe something else.
Here is some code that doesn't work but I think shows the logic:
x = 'http://test.com/lalala-134'
print x['-':0] # beginning at the end of the string, return everything before '-'
Note that the number at the end will vary in size so I can't set an exact count from the end of the string.
You are looking for str.rsplit(), with a limit:
print x.rsplit('-', 1)[0]
.rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.
Another option is to use str.rpartition(), which will only ever split just once:
print x.rpartition('-')[0]
For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().
Demo:
>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'
and the same with str.rpartition()
>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'
Difference between split and partition is split returns the list without delimiter and will split where ever it gets delimiter in string i.e.
x = 'http://test.com/lalala-134-431'
a,b,c = x.split(-)
print(a)
"http://test.com/lalala"
print(b)
"134"
print(c)
"431"
and partition will divide the string with only first delimiter and will only return 3 values in list
x = 'http://test.com/lalala-134-431'
a,b,c = x.partition('-')
print(a)
"http://test.com/lalala"
print(b)
"-"
print(c)
"134-431"
so as you want last value you can use rpartition it works in same way but it will find delimiter from end of string
x = 'http://test.com/lalala-134-431'
a,b,c = x.rpartition('-')
print(a)
"http://test.com/lalala-134"
print(b)
"-"
print(c)
"431"