This question already has answers here:
Why doesn't calling a string method (such as .replace or .strip) modify (mutate) the string?
(3 answers)
Closed 2 years ago.
The following code should take strings in for form of #d# and roll a random number based on the dice then replace #d# with #.
For example 1d6 would roll 1 6-sided die and replace 1d6 with, say, a 5.
# Turn dice notation into a number
def parse_dice(string):
# Replace all dice notations #d# with a number #
matches = re.findall("[0-9]+d[0-9]+", string)
for match in matches:
a = match.split("d", 1)[0]
b = match.split("d", 1)[1]
roll = str(roll_dice(int(a), int(b)))
print("String is: " + string + "\nThe match is: " + match + "\nI'll replace it with the roll: " + roll)
string.replace(match, roll)
print("After replacing I got: " + string)
# Parse any leftover math tacked on
number = eval(string)
return number
The print statements are for testing. Here's an example output:
String is: 1d6
The match is: 1d6
I'll replace it with the roll: 2
After replacing I got: 1d6
For some reason, even though the string matches the string I'm replacing EXACTLY it won't replace it so at the end I'm running eval("1d6") instead of eval("5")
replace() returns a copy of the string where all occurrences of a substring is replaced.
You cannot mutate (modify) a string in python. Even if you want badly. Strings are immutable datatype by design, so, please, create a new string. The proper use is
string2 = string.replace(....
well, as Thierry suggested, you can
store that new string in the same variable
string = string.replace(...
Related
This question already has answers here:
Efficient way to add spaces between characters in a string
(5 answers)
Closed 1 year ago.
So i am making a very simple python program which takes a string as input from user and adds a '-' between every character but the problem is it adds it to last one too but i don't want that...
Here's the code:
string = input("Enter the string to be traversed: ")
for ch in string:
print(ch , end = "-")
Output:
Enter the string to be traversed: helloworld
h-e-l-l-o-w-o-r-l-d-
I don't want it to print '-' after the last character...
This is a common problem and there is a string method to deal with it. Instead of a for loop, join the characters with a dash.
string = input("Enter the string to be traversed: ")
print("-".join(string))
.join will work with anything that iterates strings. In your case, a string does that, character by character. But a list or tuple would work as well.
This question already has answers here:
Print without space in python 3
(6 answers)
How to print without a newline or space
(26 answers)
Closed 1 year ago.
This is my code:
length = len(input("What is your name?\n"))
print("The length of your name is ",length,".")
Now, this is my output:
What is your name?
Shary
The length of your name is 5 .
I would like my output to be like this "The length of your name is 5."
As you can imagine, by placing a comma next to the Integer length, I have an extra space I would like to take care of. I am new to Python so I do not really know how to solve this.
Any help would be greatly appreciated.
By default, print puts spaces between each of the arguments it receives.
There are a number of ways you can get the behavior you want. Here are a few different options:
# The 'sep' argument changes what separator is used between args:
print("The length of your name is ", length, ".", sep='')
# String concatenation doesn't implicitly add any separators:
print("The length of your name is " + str(length) + ".")
# String formatting similarly lets you be more precise with your spacing:
print("The length of your name is {}.".format(length))
print(f"The length of your name is {length}.")
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:
Removing numbers from string [closed]
(8 answers)
Closed 5 years ago.
Im looking to remove every single number in a string. More specifically, i'm looking to remove all numbers in the following codes string
Comp_String = "xxf1,aff242342"
how can one do this. (Obviously inside the code). I have found many answers to questions about removing the actual parts of the code that are letters but not numbers. Please explain aswell what your code is actually doing
You can find the answer here
Removing numbers from string
From this answer:
comp_string = "xxf1,aff242342"
new_string = ''.join([i for i in comp_string if not i.isdigit()])
It creates a new string using .join from a list. That list is created using a list comprehension that iterates through characters in your original string, and excludes all digits.
This will remove any characters that ARE NOT letters, by going through each character and only adding it to the output if it is a letter:
output_string = ""
for char in Comp_String:
if char.isalpha():
output_string = output_string + char
This will remove any characters that ARE numbers, by going through each character and only adding it to the output if it is not a number:
output_string = ""
for char in Comp_String:
if not char.isdigit():
output_string = output_string + char
You can do it with regular expressions using the https://docs.python.org/3.6/library/re.html module. The only regex you need is \d, which notates digits.
from re import sub
comp_string = "xxf1,aff242342"
print(sub(pattern=r"\d", repl=r"", string=comp_string))
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'