简体   繁体   English

如何在Python字符串中设置字符?

[英]How do I set characters in a Python string?

I have a function that decrements a whole number parameter represented by a string. 我有一个函数,可以减少由字符串表示的整数参数。 For instance, if I pass in the string "100", it should return "99." 例如,如果我输入字符串“ 100”,则它应返回“ 99”。

def dec(s):
    i = len(s) - 1
    myString = ""
    while (i >= 0):
        if s[i] == '0':
            s[i] = '9'
            i -= 1
        else:
            s[i] = chr(int(s[i]) - 1)
            break
    return s

However, Python issues this error. 但是,Python会发出此错误。

s[i] = '9'
TypeError: 'str' object does not support item assignment 

I am assuming that s[i] cannot be treated as an lvalue. 我假设s[i]不能被视为左值。 What is a solution around this? 对此有什么解决方案?

You can do: 你可以做:

s = s[:i] + "9" + s[i+1:]

This takes the part of the string before character index i , appends a 9 , then appends the part of the string after character index i . 这需要前字符索引字符串的一部分i ,附加一个9 ,然后追加字符索引之后的字符串的一部分i However, doing a lot of string appends like this is not terribly efficient. 但是,像这样进行大量的字符串追加并非十分有效。

The other answer is that if you're dealing with numbers, why not actually use numbers instead of strings? 另一个答案是,如果要处理数字,为什么不实际使用数字而不是字符串呢?

def dec(s):
    return str(int(s) - 1)

You can't. 你不能 In Python, strings are immutable -- once created, they can't be changed. 在Python中,字符串是不可变的-创建后就无法更改。

You have two options without changing your function entirely. 您有两个选择,而不必完全更改功能。

Convert the string to a list and back: 将字符串转换为列表并返回:

def dec(s):
    s = list(s)
    i = len(s) - 1
    myString = ""
    while (i >= 0):
        if s[i] == '0':
            s[i] = '9'
            i -= 1
        else:
            s[i] = chr(int(s[i]) - 1)
            break
    return ''.join(s)

Create a new string each time you want to make a change: 每次要进行更改时,请创建一个新字符串:

def dec(s):
    i = len(s) - 1
    myString = ""
    while (i >= 0):
        if s[i] == '0':
            s = s[:i] + "9" + s[i+1:]
            i -= 1
        else:
            s = s[:i] + chr(int(s[i]) - 1) + s[i+1:]
            break
    return s

I'm not sure why you are playing with the string character by character. 我不确定您为什么要逐个字符串地玩游戏。 Isn't this simpler? 这不是更简单吗?

def decrement_string(s):
    try:
      i = int(s)
      i = i - 1
      return str(i)
    except:
      # do something else
      return "that's no number!"

while True:
  s = raw_input("give me a number and I'll decrement it for you: ")
  print decrement_string(s)

The solution to your specific problem of "decrementing" strings is to convert s to an int with int(s) , decrease that, and convert back to a str: str(int(s)-1) . 解决您的“减少”字符串的特定问题的解决方案是将s转换为具有int(s) ,将其减少,然后再转换回str: str(int(s)-1)

In [175]: str(int('100')-1)
Out[175]: '99'

The general solution is to not attempt to alter the elements of a string; 一般的解决方案是不要尝试更改字符串的元素; use some other type to represent your work, and convert to a string as the last step. 使用其他类型来表示您的作品,并最后转换为字符串。

Python strings are immutable so you cannot modify them. Python字符串是不可变的,因此您无法对其进行修改。 You have to create a new string that contains the value that you need. 您必须创建一个包含所需值的新字符串。 You are better off converting the string to an integer, decrementing it, and then converting it back to an integer again. 最好将字符串转换为整数,将其递减,然后再次将其转换回整数。

The reason for immutable strings is primarily efficiency. 字符串不变的原因主要是效率。

Strings aren't mutable, but lists are. 字符串不是可变的,但列表是可变的。 You can easily convert the string to a list of individual characters: 您可以轻松地将字符串转换为单个字符的列表:

l = list(s)

Then convert it back: 然后将其转换回:

s = ''.join(l)

Since you're working with a numeric string there are more direct approaches, but this answer works for the general case. 由于您使用的是数字字符串,因此有更多直接方法,但是此答案适用于一般情况。

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

相关问题 如何在Python中替换字符串中的字符? - How do I replace characters in a string in Python? 在Python中,我如何搜索和计数/打印列表中每个项目/字符串中的一组特定字符 - In Python how do I search for and count/print a specific set of characters in each item/string in a list 如何从 python 中的字符串中的特定 position 读取一组字符 - How do I read a set of characters from a specific position in a string in python (Python)如何将字符添加到集合中的某个字符串? - (Python) How can I add characters to a certain string in a set? 如何在Python 2字符串中设置和保留字符的属性? - How can I set and retain attributes on characters in a Python 2 string? 如何从Python的字符串中提取字符? - How do I extract characters from a string in Python? 如何在给定不需要的字符列表的情况下删除字符串? 蟒蛇 - How do I strip a string given a list of unwanted characters? Python 如何从 python 中的字符串中删除多个随机字符 - How do I remove multiple random characters from a string in python 在 Pandas Python 中,如何替换字符串列中的字符? - In Pandas Python how do i replace Characters in String column? 如何在编码字符串中添加字符? 蟒蛇 - How do I add characters to an encoded string? Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM