简体   繁体   English

如何增加字符串中间的数字?

[英]How can I increase a number in the middle of a string?

So, I have this string:所以,我有这个字符串:

string = ("book_volume_2")

and I want to increase that number to 3, 4 and so on, up to 6我想将该数字增加到 3、4 等等,最多 6

I've tried我试过了

book = ("book_volume_")
book_plus = (book + str(book +1))

I get something like我得到类似的东西

book_volume_2book_volume22

but I'm expecting:但我期待:

book_volume_3

Is there any way to obtain this?有没有办法获得这个?

Thanks!谢谢!

What you want to use are f-strings您要使用的是f-strings

for i in range(1,5):
    print(f'book_volume_{i}')

I've applied the logic in a for-loop to show how it works.我已经在 for 循环中应用了逻辑来展示它是如何工作的。

But basically, whatever is inside the curly brackets is not considered a string.但基本上,大括号内的任何内容都不会被视为字符串。

eg例如

if I have function myFunc:如果我有 function myFunc:

def myFunc():
    return 5

And then I do print(f'book_volume_{myFunc()}')然后我做print(f'book_volume_{myFunc()}')

The result will be: book_volume_5结果将是: book_volume_5

You need to make the numeric part of the string an integer if you want to increment it.如果要增加字符串的数字部分,则需要将其设为 integer。 Assuming the book name and number are always separated by an underscore you could do something like:假设书名和编号始终用下划线分隔,您可以执行以下操作:

mystr = "book_volume_2"
book, sep, vol = mystr.rpartition('_')
vol = str(int(vol) + 1)
my_new_str = ''.join([book, sep, vol])

> 'book_volume_3'

If you have a string string = "book_volume_2" where the last character is a digit, then you can replace that with the next number like this:如果您有一个字符串string = "book_volume_2" ,其中最后一个字符是数字,那么您可以将其替换为下一个数字,如下所示:

def next_number(book):
    base = book[:-1]
    digit = int(book[-1])
    return base + str(digit + 1)

print(next_number('book_volume_2'))
string = "book_volume_" + input('Enter volume number: ')
print(string) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何增加难度? (例如增加敌人的速度,增加敌人的数量) - How can I increase difficulty? (e.g. increase speed of enemies, increase number of enemies) 如何从字符串中间获取2个字符? - How can I get 2 characters from the middle of a string? 如何在python中永久增加一个数字(变量)? - How can I permanently increase a number (variable) in python? 如何删除列表中的每个第一个数字、最后一个数字和中间数字? - How can I remove every the first number, last number and middle number in a list? 如何在字符串中间用前导零填充数字? - How to pad a number with leading zeros in the middle of a string? 如何拆分和删除 python 中字符串中间的数字? - How to split & remove a number in the middle of string in a python? 如何在代码中提高字符串生成的速度? - How can I increase the speed of string generating in my code? 如何用 pandas dataframe 中的字符串中间的数字零 (0) 替换破折号 (-) 的所有实例? - How do i replace all instances of a dash (-) with the number zero (0) in the middle of a string in pandas dataframe? 如何在 Python 中编写正则表达式以删除字符串中间数字的前导零 - How do I write a Regex in Python to remove leading zeros for a number in the middle of a string 如何计算字符串中数字的数量 - How can I count the number of numbers in a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM